File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.775: download - view: text, annotated - select for diffs
Sat Mar 21 21:41:14 2009 UTC (15 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Fixed typo in title style from revision 1.773

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.775 2009/03/21 21:41:14 bisitz 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::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript" >
  410:     var stdeditbrowser;
  411:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  412:         var url = '/adm/pickstudent?';
  413:         var filter;
  414: 	if (!ignorefilter) {
  415: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  416: 	}
  417:         if (filter != null) {
  418:            if (filter != '') {
  419:                url += 'filter='+filter+'&';
  420: 	   }
  421:         }
  422:         url += 'form=' + formname + '&unameelement='+uname+
  423:                                     '&udomelement='+udom;
  424: 	if (roleflag) { url+="&roles=1"; }
  425:         var title = 'Student_Browser';
  426:         var options = 'scrollbars=1,resizable=1,menubar=0';
  427:         options += ',width=700,height=600';
  428:         stdeditbrowser = open(url,title,options,'1');
  429:         stdeditbrowser.focus();
  430:     }
  431: </script>
  432: ENDSTDBRW
  433: }
  434: 
  435: sub selectstudent_link {
  436:    my ($form,$unameele,$udomele)=@_;
  437:    if ($env{'request.course.id'}) {  
  438:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  439: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  440: 					'/'.$env{'request.course.sec'})) {
  441: 	   return '';
  442:        }
  443:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  444:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  445:    }
  446:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  447:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  448:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  449:    }
  450:    return '';
  451: }
  452: 
  453: sub authorbrowser_javascript {
  454:     return <<"ENDAUTHORBRW";
  455: <script type="text/javascript">
  456: var stdeditbrowser;
  457: 
  458: function openauthorbrowser(formname,udom) {
  459:     var url = '/adm/pickauthor?';
  460:     url += 'form='+formname+'&roledom='+udom;
  461:     var title = 'Author_Browser';
  462:     var options = 'scrollbars=1,resizable=1,menubar=0';
  463:     options += ',width=700,height=600';
  464:     stdeditbrowser = open(url,title,options,'1');
  465:     stdeditbrowser.focus();
  466: }
  467: 
  468: </script>
  469: ENDAUTHORBRW
  470: }
  471: 
  472: sub coursebrowser_javascript {
  473:     my ($domainfilter,$sec_element,$formname)=@_;
  474:     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');
  475:    my $output = '
  476: <script type="text/javascript">
  477:     var stdeditbrowser;'."\n";
  478:    $output .= <<"ENDSTDBRW";
  479:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  480:         var url = '/adm/pickcourse?';
  481:         var domainfilter = '';
  482:         var formid = getFormIdByName(formname);
  483:         if (formid > -1) {
  484:             var domid = getIndexByName(formid,udom);
  485:             if (domid > -1) {
  486:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  487:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  488:                 }
  489:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  490:                     domainfilter=document.forms[formid].elements[domid].value;
  491:                 }
  492:             }
  493:         }
  494:         if (domainfilter != null) {
  495:            if (domainfilter != '') {
  496:                url += 'domainfilter='+domainfilter+'&';
  497: 	   }
  498:         }
  499:         url += 'form=' + formname + '&cnumelement='+uname+
  500: 	                            '&cdomelement='+udom+
  501:                                     '&cnameelement='+desc;
  502:         if (extra_element !=null && extra_element != '') {
  503:             if (formname == 'rolechoice' || formname == 'studentform') {
  504:                 url += '&roleelement='+extra_element;
  505:                 if (domainfilter == null || domainfilter == '') {
  506:                     url += '&domainfilter='+extra_element;
  507:                 }
  508:             }
  509:             else {
  510:                 if (formname == 'portform') {
  511:                     url += '&setroles='+extra_element;
  512:                 }
  513:             }     
  514:         }
  515:         if (multflag !=null && multflag != '') {
  516:             url += '&multiple='+multflag;
  517:         }
  518:         if (crstype == 'Course/Group') {
  519:             if (formname == 'cu') {
  520:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  521:                 if (crstype == "") {
  522:                     alert("$crs_or_grp_alert");
  523:                     return;
  524:                 }
  525:             }
  526:         }
  527:         if (crstype !=null && crstype != '') {
  528:             url += '&type='+crstype;
  529:         }
  530:         var title = 'Course_Browser';
  531:         var options = 'scrollbars=1,resizable=1,menubar=0';
  532:         options += ',width=700,height=600';
  533:         stdeditbrowser = open(url,title,options,'1');
  534:         stdeditbrowser.focus();
  535:     }
  536: 
  537:     function getFormIdByName(formname) {
  538:         for (var i=0;i<document.forms.length;i++) {
  539:             if (document.forms[i].name == formname) {
  540:                 return i;
  541:             }
  542:         }
  543:         return -1; 
  544:     }
  545: 
  546:     function getIndexByName(formid,item) {
  547:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  548:             if (document.forms[formid].elements[i].name == item) {
  549:                 return i;
  550:             }
  551:         }
  552:         return -1;
  553:     }
  554: ENDSTDBRW
  555:     if ($sec_element ne '') {
  556:         $output .= &setsec_javascript($sec_element,$formname);
  557:     }
  558:     $output .= '
  559: </script>';
  560:     return $output;
  561: }
  562: 
  563: sub setsec_javascript {
  564:     my ($sec_element,$formname) = @_;
  565:     my $setsections = qq|
  566: function setSect(sectionlist) {
  567:     var sectionsArray = new Array();
  568:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  569:         sectionsArray = sectionlist.split(",");
  570:     }
  571:     var numSections = sectionsArray.length;
  572:     document.$formname.$sec_element.length = 0;
  573:     if (numSections == 0) {
  574:         document.$formname.$sec_element.multiple=false;
  575:         document.$formname.$sec_element.size=1;
  576:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  577:     } else {
  578:         if (numSections == 1) {
  579:             document.$formname.$sec_element.multiple=false;
  580:             document.$formname.$sec_element.size=1;
  581:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  582:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  583:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  584:         } else {
  585:             for (var i=0; i<numSections; i++) {
  586:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  587:             }
  588:             document.$formname.$sec_element.multiple=true
  589:             if (numSections < 3) {
  590:                 document.$formname.$sec_element.size=numSections;
  591:             } else {
  592:                 document.$formname.$sec_element.size=3;
  593:             }
  594:             document.$formname.$sec_element.options[0].selected = false
  595:         }
  596:     }
  597: }
  598: |;
  599:     return $setsections;
  600: }
  601: 
  602: 
  603: sub selectcourse_link {
  604:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  605:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  606:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  607: }
  608: 
  609: sub selectauthor_link {
  610:    my ($form,$udom)=@_;
  611:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  612:           &mt('Select Author').'</a>';
  613: }
  614: 
  615: sub check_uncheck_jscript {
  616:     my $jscript = <<"ENDSCRT";
  617: function checkAll(field) {
  618:     if (field.length > 0) {
  619:         for (i = 0; i < field.length; i++) {
  620:             field[i].checked = true ;
  621:         }
  622:     } else {
  623:         field.checked = true
  624:     }
  625: }
  626:  
  627: function uncheckAll(field) {
  628:     if (field.length > 0) {
  629:         for (i = 0; i < field.length; i++) {
  630:             field[i].checked = false ;
  631:         }
  632:     } else {
  633:         field.checked = false ;
  634:     }
  635: }
  636: ENDSCRT
  637:     return $jscript;
  638: }
  639: 
  640: sub select_timezone {
  641:    my ($name,$selected,$onchange,$includeempty)=@_;
  642:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  643:    if ($includeempty) {
  644:        $output .= '<option value=""';
  645:        if (($selected eq '') || ($selected eq 'local')) {
  646:            $output .= ' selected="selected" ';
  647:        }
  648:        $output .= '> </option>';
  649:    }
  650:    my @timezones = DateTime::TimeZone->all_names;
  651:    foreach my $tzone (@timezones) {
  652:        $output.= '<option value="'.$tzone.'"';
  653:        if ($tzone eq $selected) {
  654:            $output.=' selected="selected"';
  655:        }
  656:        $output.=">$tzone</option>\n";
  657:    }
  658:    $output.="</select>";
  659:    return $output;
  660: }
  661: 
  662: sub select_datelocale {
  663:     my ($name,$selected,$onchange,$includeempty)=@_;
  664:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  665:     if ($includeempty) {
  666:         $output .= '<option value=""';
  667:         if ($selected eq '') {
  668:             $output .= ' selected="selected" ';
  669:         }
  670:         $output .= '> </option>';
  671:     }
  672:     my (@possibles,%locale_names);
  673:     my @locales = DateTime::Locale::Catalog::Locales;
  674:     foreach my $locale (@locales) {
  675:         if (ref($locale) eq 'HASH') {
  676:             my $id = $locale->{'id'};
  677:             if ($id ne '') {
  678:                 my $en_terr = $locale->{'en_territory'};
  679:                 my $native_terr = $locale->{'native_territory'};
  680:                 my @languages = &Apache::lonlocal::preferred_languages();
  681:                 if (grep(/^en$/,@languages) || !@languages) {
  682:                     if ($en_terr ne '') {
  683:                         $locale_names{$id} = '('.$en_terr.')';
  684:                     } elsif ($native_terr ne '') {
  685:                         $locale_names{$id} = $native_terr;
  686:                     }
  687:                 } else {
  688:                     if ($native_terr ne '') {
  689:                         $locale_names{$id} = $native_terr.' ';
  690:                     } elsif ($en_terr ne '') {
  691:                         $locale_names{$id} = '('.$en_terr.')';
  692:                     }
  693:                 }
  694:                 push (@possibles,$id);
  695:             }
  696:         }
  697:     }
  698:     foreach my $item (sort(@possibles)) {
  699:         $output.= '<option value="'.$item.'"';
  700:         if ($item eq $selected) {
  701:             $output.=' selected="selected"';
  702:         }
  703:         $output.=">$item";
  704:         if ($locale_names{$item} ne '') {
  705:             $output.="  $locale_names{$item}</option>\n";
  706:         }
  707:         $output.="</option>\n";
  708:     }
  709:     $output.="</select>";
  710:     return $output;
  711: }
  712: 
  713: =pod
  714: 
  715: =item * &linked_select_forms(...)
  716: 
  717: linked_select_forms returns a string containing a <script></script> block
  718: and html for two <select> menus.  The select menus will be linked in that
  719: changing the value of the first menu will result in new values being placed
  720: in the second menu.  The values in the select menu will appear in alphabetical
  721: order unless a defined order is provided.
  722: 
  723: linked_select_forms takes the following ordered inputs:
  724: 
  725: =over 4
  726: 
  727: =item * $formname, the name of the <form> tag
  728: 
  729: =item * $middletext, the text which appears between the <select> tags
  730: 
  731: =item * $firstdefault, the default value for the first menu
  732: 
  733: =item * $firstselectname, the name of the first <select> tag
  734: 
  735: =item * $secondselectname, the name of the second <select> tag
  736: 
  737: =item * $hashref, a reference to a hash containing the data for the menus.
  738: 
  739: =item * $menuorder, the order of values in the first menu
  740: 
  741: =back 
  742: 
  743: Below is an example of such a hash.  Only the 'text', 'default', and 
  744: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  745: values for the first select menu.  The text that coincides with the 
  746: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  747: and text for the second menu are given in the hash pointed to by 
  748: $menu{$choice1}->{'select2'}.  
  749: 
  750:  my %menu = ( A1 => { text =>"Choice A1" ,
  751:                        default => "B3",
  752:                        select2 => { 
  753:                            B1 => "Choice B1",
  754:                            B2 => "Choice B2",
  755:                            B3 => "Choice B3",
  756:                            B4 => "Choice B4"
  757:                            },
  758:                        order => ['B4','B3','B1','B2'],
  759:                    },
  760:                A2 => { text =>"Choice A2" ,
  761:                        default => "C2",
  762:                        select2 => { 
  763:                            C1 => "Choice C1",
  764:                            C2 => "Choice C2",
  765:                            C3 => "Choice C3"
  766:                            },
  767:                        order => ['C2','C1','C3'],
  768:                    },
  769:                A3 => { text =>"Choice A3" ,
  770:                        default => "D6",
  771:                        select2 => { 
  772:                            D1 => "Choice D1",
  773:                            D2 => "Choice D2",
  774:                            D3 => "Choice D3",
  775:                            D4 => "Choice D4",
  776:                            D5 => "Choice D5",
  777:                            D6 => "Choice D6",
  778:                            D7 => "Choice D7"
  779:                            },
  780:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  781:                    }
  782:                );
  783: 
  784: =cut
  785: 
  786: sub linked_select_forms {
  787:     my ($formname,
  788:         $middletext,
  789:         $firstdefault,
  790:         $firstselectname,
  791:         $secondselectname, 
  792:         $hashref,
  793:         $menuorder,
  794:         ) = @_;
  795:     my $second = "document.$formname.$secondselectname";
  796:     my $first = "document.$formname.$firstselectname";
  797:     # output the javascript to do the changing
  798:     my $result = '';
  799:     $result.="<script type=\"text/javascript\">\n";
  800:     $result.="var select2data = new Object();\n";
  801:     $" = '","';
  802:     my $debug = '';
  803:     foreach my $s1 (sort(keys(%$hashref))) {
  804:         $result.="select2data.d_$s1 = new Object();\n";        
  805:         $result.="select2data.d_$s1.def = new String('".
  806:             $hashref->{$s1}->{'default'}."');\n";
  807:         $result.="select2data.d_$s1.values = new Array(";
  808:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  809:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  810:             @s2values = @{$hashref->{$s1}->{'order'}};
  811:         }
  812:         $result.="\"@s2values\");\n";
  813:         $result.="select2data.d_$s1.texts = new Array(";        
  814:         my @s2texts;
  815:         foreach my $value (@s2values) {
  816:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  817:         }
  818:         $result.="\"@s2texts\");\n";
  819:     }
  820:     $"=' ';
  821:     $result.= <<"END";
  822: 
  823: function select1_changed() {
  824:     // Determine new choice
  825:     var newvalue = "d_" + $first.value;
  826:     // update select2
  827:     var values     = select2data[newvalue].values;
  828:     var texts      = select2data[newvalue].texts;
  829:     var select2def = select2data[newvalue].def;
  830:     var i;
  831:     // out with the old
  832:     for (i = 0; i < $second.options.length; i++) {
  833:         $second.options[i] = null;
  834:     }
  835:     // in with the nuclear
  836:     for (i=0;i<values.length; i++) {
  837:         $second.options[i] = new Option(values[i]);
  838:         $second.options[i].value = values[i];
  839:         $second.options[i].text = texts[i];
  840:         if (values[i] == select2def) {
  841:             $second.options[i].selected = true;
  842:         }
  843:     }
  844: }
  845: </script>
  846: END
  847:     # output the initial values for the selection lists
  848:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  849:     my @order = sort(keys(%{$hashref}));
  850:     if (ref($menuorder) eq 'ARRAY') {
  851:         @order = @{$menuorder};
  852:     }
  853:     foreach my $value (@order) {
  854:         $result.="    <option value=\"$value\" ";
  855:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  856:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  857:     }
  858:     $result .= "</select>\n";
  859:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  860:     $result .= $middletext;
  861:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  862:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  863:     
  864:     my @secondorder = sort(keys(%select2));
  865:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  866:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  867:     }
  868:     foreach my $value (@secondorder) {
  869:         $result.="    <option value=\"$value\" ";        
  870:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  871:         $result.=">".&mt($select2{$value})."</option>\n";
  872:     }
  873:     $result .= "</select>\n";
  874:     #    return $debug;
  875:     return $result;
  876: }   #  end of sub linked_select_forms {
  877: 
  878: =pod
  879: 
  880: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  881: 
  882: Returns a string corresponding to an HTML link to the given help
  883: $topic, where $topic corresponds to the name of a .tex file in
  884: /home/httpd/html/adm/help/tex, with underscores replaced by
  885: spaces. 
  886: 
  887: $text will optionally be linked to the same topic, allowing you to
  888: link text in addition to the graphic. If you do not want to link
  889: text, but wish to specify one of the later parameters, pass an
  890: empty string. 
  891: 
  892: $stayOnPage is a value that will be interpreted as a boolean. If true,
  893: the link will not open a new window. If false, the link will open
  894: a new window using Javascript. (Default is false.) 
  895: 
  896: $width and $height are optional numerical parameters that will
  897: override the width and height of the popped up window, which may
  898: be useful for certain help topics with big pictures included. 
  899: 
  900: =cut
  901: 
  902: sub help_open_topic {
  903:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  904:     $text = "" if (not defined $text);
  905:     $stayOnPage = 0 if (not defined $stayOnPage);
  906:     if ($env{'browser.interface'} eq 'textual') {
  907: 	$stayOnPage=1;
  908:     }
  909:     $width = 350 if (not defined $width);
  910:     $height = 400 if (not defined $height);
  911:     my $filename = $topic;
  912:     $filename =~ s/ /_/g;
  913: 
  914:     my $template = "";
  915:     my $link;
  916:     
  917:     $topic=~s/\W/\_/g;
  918: 
  919:     if (!$stayOnPage) {
  920: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  921:     } else {
  922: 	$link = "/adm/help/${filename}.hlp";
  923:     }
  924: 
  925:     # Add the text
  926:     if ($text ne "") {	
  927: 	$template.='<span class="LC_help_open_topic">'
  928:                   .'<a target="_top" href="'.$link.'">'
  929:                   .$text.'</a>';
  930:     }
  931: 
  932:     # (Always) Add the graphic
  933:     my $title = &mt('Online Help');
  934:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  935:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  936:               .'<img src="'.$helpicon.'" border="0"'
  937:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  938:               .' title="'.$title.'"'
  939:               .' /></a>';
  940:     if ($text ne "") {	
  941:         $template.='</span>';
  942:     }
  943:     return $template;
  944: 
  945: }
  946: 
  947: # This is a quicky function for Latex cheatsheet editing, since it 
  948: # appears in at least four places
  949: sub helpLatexCheatsheet {
  950:     my ($topic,$text,$not_author) = @_;
  951:     my $out;
  952:     my $addOther = '';
  953:     if ($topic) {
  954: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
  955: 							       undef, undef, 600).
  956: 								   '</span> ';
  957:     }
  958:     $out = '<span>' # Start cheatsheet
  959: 	  .$addOther
  960:           .'<span>'
  961: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
  962: 					       undef,undef,600)
  963: 	  .'</span> <span>'
  964: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
  965: 					       undef,undef,600)
  966: 	  .'</span>';
  967:     unless ($not_author) {
  968:         $out .= ' <span>'
  969: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
  970: 	                                            undef,undef,600)
  971: 	       .'</span>';
  972:     }
  973:     $out .= '</span>'; # End cheatsheet
  974:     return $out;
  975: }
  976: 
  977: sub general_help {
  978:     my $helptopic='Student_Intro';
  979:     if ($env{'request.role'}=~/^(ca|au)/) {
  980: 	$helptopic='Authoring_Intro';
  981:     } elsif ($env{'request.role'}=~/^cc/) {
  982: 	$helptopic='Course_Coordination_Intro';
  983:     } elsif ($env{'request.role'}=~/^dc/) {
  984:         $helptopic='Domain_Coordination_Intro';
  985:     }
  986:     return $helptopic;
  987: }
  988: 
  989: sub update_help_link {
  990:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  991:     my $origurl = $ENV{'REQUEST_URI'};
  992:     $origurl=~s|^/~|/priv/|;
  993:     my $timestamp = time;
  994:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  995:         $$datum = &escape($$datum);
  996:     }
  997: 
  998:     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";
  999:     my $output .= <<"ENDOUTPUT";
 1000: <script type="text/javascript">
 1001: banner_link = '$banner_link';
 1002: </script>
 1003: ENDOUTPUT
 1004:     return $output;
 1005: }
 1006: 
 1007: # now just updates the help link and generates a blue icon
 1008: sub help_open_menu {
 1009:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1010: 	= @_;    
 1011:     $stayOnPage = 0 if (not defined $stayOnPage);
 1012:     # only use pop-up help (stayOnPage == 0)
 1013:     # if environment.remote is on (using remote control UI)
 1014:     if ($env{'browser.interface'} eq 'textual' ||
 1015:     	$env{'environment.remote'} eq 'off' ) {
 1016:         $stayOnPage=1;
 1017:     }
 1018:     my $output;
 1019:     if ($component_help) {
 1020: 	if (!$text) {
 1021: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1022: 				       $width,$height);
 1023: 	} else {
 1024: 	    my $help_text;
 1025: 	    $help_text=&unescape($topic);
 1026: 	    $output='<table><tr><td>'.
 1027: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1028: 				 $width,$height).'</td></tr></table>';
 1029: 	}
 1030:     }
 1031:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1032:     return $output.$banner_link;
 1033: }
 1034: 
 1035: sub top_nav_help {
 1036:     my ($text) = @_;
 1037:     $text = &mt($text);
 1038:     my $stay_on_page = 
 1039: 	($env{'browser.interface'}  eq 'textual' ||
 1040: 	 $env{'environment.remote'} eq 'off' );
 1041:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1042: 	                     : "javascript:helpMenu('open')";
 1043:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1044: 
 1045:     my $title = &mt('Get help');
 1046: 
 1047:     return <<"END";
 1048: $banner_link
 1049:  <a href="$link" title="$title">$text</a>
 1050: END
 1051: }
 1052: 
 1053: sub help_menu_js {
 1054:     my ($text) = @_;
 1055: 
 1056:     my $stayOnPage = 
 1057: 	($env{'browser.interface'}  eq 'textual' ||
 1058: 	 $env{'environment.remote'} eq 'off' );
 1059: 
 1060:     my $width = 620;
 1061:     my $height = 600;
 1062:     my $helptopic=&general_help();
 1063:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1064:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1065:     my $start_page =
 1066:         &Apache::loncommon::start_page('Help Menu', undef,
 1067: 				       {'frameset'    => 1,
 1068: 					'js_ready'    => 1,
 1069: 					'add_entries' => {
 1070: 					    'border' => '0',
 1071: 					    'rows'   => "110,*",},});
 1072:     my $end_page =
 1073:         &Apache::loncommon::end_page({'frameset' => 1,
 1074: 				      'js_ready' => 1,});
 1075: 
 1076:     my $template .= <<"ENDTEMPLATE";
 1077: <script type="text/javascript">
 1078: // <!-- BEGIN LON-CAPA Internal
 1079: // <![CDATA[
 1080: var banner_link = '';
 1081: function helpMenu(target) {
 1082:     var caller = this;
 1083:     if (target == 'open') {
 1084:         var newWindow = null;
 1085:         try {
 1086:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1087:         }
 1088:         catch(error) {
 1089:             writeHelp(caller);
 1090:             return;
 1091:         }
 1092:         if (newWindow) {
 1093:             caller = newWindow;
 1094:         }
 1095:     }
 1096:     writeHelp(caller);
 1097:     return;
 1098: }
 1099: function writeHelp(caller) {
 1100:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1101:     caller.document.close()
 1102:     caller.focus()
 1103: }
 1104: // ]]>
 1105: // END LON-CAPA Internal -->
 1106: </script>
 1107: ENDTEMPLATE
 1108:     return $template;
 1109: }
 1110: 
 1111: sub help_open_bug {
 1112:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1113:     unless ($env{'user.adv'}) { return ''; }
 1114:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1115:     $text = "" if (not defined $text);
 1116:     $stayOnPage = 0 if (not defined $stayOnPage);
 1117:     if ($env{'browser.interface'} eq 'textual' ||
 1118: 	$env{'environment.remote'} eq 'off' ) {
 1119: 	$stayOnPage=1;
 1120:     }
 1121:     $width = 600 if (not defined $width);
 1122:     $height = 600 if (not defined $height);
 1123: 
 1124:     $topic=~s/\W+/\+/g;
 1125:     my $link='';
 1126:     my $template='';
 1127:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1128: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1129:     if (!$stayOnPage)
 1130:     {
 1131: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1132:     }
 1133:     else
 1134:     {
 1135: 	$link = $url;
 1136:     }
 1137:     # Add the text
 1138:     if ($text ne "")
 1139:     {
 1140: 	$template .= 
 1141:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1142:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1143:     }
 1144: 
 1145:     # Add the graphic
 1146:     my $title = &mt('Report a Bug');
 1147:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1148:     $template .= <<"ENDTEMPLATE";
 1149:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1150: ENDTEMPLATE
 1151:     if ($text ne '') { $template.='</td></tr></table>' };
 1152:     return $template;
 1153: 
 1154: }
 1155: 
 1156: sub help_open_faq {
 1157:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1158:     unless ($env{'user.adv'}) { return ''; }
 1159:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1160:     $text = "" if (not defined $text);
 1161:     $stayOnPage = 0 if (not defined $stayOnPage);
 1162:     if ($env{'browser.interface'} eq 'textual' ||
 1163: 	$env{'environment.remote'} eq 'off' ) {
 1164: 	$stayOnPage=1;
 1165:     }
 1166:     $width = 350 if (not defined $width);
 1167:     $height = 400 if (not defined $height);
 1168: 
 1169:     $topic=~s/\W+/\+/g;
 1170:     my $link='';
 1171:     my $template='';
 1172:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1173:     if (!$stayOnPage)
 1174:     {
 1175: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1176:     }
 1177:     else
 1178:     {
 1179: 	$link = $url;
 1180:     }
 1181: 
 1182:     # Add the text
 1183:     if ($text ne "")
 1184:     {
 1185: 	$template .= 
 1186:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1187:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1188:     }
 1189: 
 1190:     # Add the graphic
 1191:     my $title = &mt('View the FAQ');
 1192:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1193:     $template .= <<"ENDTEMPLATE";
 1194:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1195: ENDTEMPLATE
 1196:     if ($text ne '') { $template.='</td></tr></table>' };
 1197:     return $template;
 1198: 
 1199: }
 1200: 
 1201: ###############################################################
 1202: ###############################################################
 1203: 
 1204: =pod
 1205: 
 1206: =item * &change_content_javascript():
 1207: 
 1208: This and the next function allow you to create small sections of an
 1209: otherwise static HTML page that you can update on the fly with
 1210: Javascript, even in Netscape 4.
 1211: 
 1212: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1213: must be written to the HTML page once. It will prove the Javascript
 1214: function "change(name, content)". Calling the change function with the
 1215: name of the section 
 1216: you want to update, matching the name passed to C<changable_area>, and
 1217: the new content you want to put in there, will put the content into
 1218: that area.
 1219: 
 1220: B<Note>: Netscape 4 only reserves enough space for the changable area
 1221: to contain room for the original contents. You need to "make space"
 1222: for whatever changes you wish to make, and be B<sure> to check your
 1223: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1224: it's adequate for updating a one-line status display, but little more.
 1225: This script will set the space to 100% width, so you only need to
 1226: worry about height in Netscape 4.
 1227: 
 1228: Modern browsers are much less limiting, and if you can commit to the
 1229: user not using Netscape 4, this feature may be used freely with
 1230: pretty much any HTML.
 1231: 
 1232: =cut
 1233: 
 1234: sub change_content_javascript {
 1235:     # If we're on Netscape 4, we need to use Layer-based code
 1236:     if ($env{'browser.type'} eq 'netscape' &&
 1237: 	$env{'browser.version'} =~ /^4\./) {
 1238: 	return (<<NETSCAPE4);
 1239: 	function change(name, content) {
 1240: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1241: 	    doc.open();
 1242: 	    doc.write(content);
 1243: 	    doc.close();
 1244: 	}
 1245: NETSCAPE4
 1246:     } else {
 1247: 	# Otherwise, we need to use semi-standards-compliant code
 1248: 	# (technically, "innerHTML" isn't standard but the equivalent
 1249: 	# is really scary, and every useful browser supports it
 1250: 	return (<<DOMBASED);
 1251: 	function change(name, content) {
 1252: 	    element = document.getElementById(name);
 1253: 	    element.innerHTML = content;
 1254: 	}
 1255: DOMBASED
 1256:     }
 1257: }
 1258: 
 1259: =pod
 1260: 
 1261: =item * &changable_area($name,$origContent):
 1262: 
 1263: This provides a "changable area" that can be modified on the fly via
 1264: the Javascript code provided in C<change_content_javascript>. $name is
 1265: the name you will use to reference the area later; do not repeat the
 1266: same name on a given HTML page more then once. $origContent is what
 1267: the area will originally contain, which can be left blank.
 1268: 
 1269: =cut
 1270: 
 1271: sub changable_area {
 1272:     my ($name, $origContent) = @_;
 1273: 
 1274:     if ($env{'browser.type'} eq 'netscape' &&
 1275: 	$env{'browser.version'} =~ /^4\./) {
 1276: 	# If this is netscape 4, we need to use the Layer tag
 1277: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1278:     } else {
 1279: 	return "<span id='$name'>$origContent</span>";
 1280:     }
 1281: }
 1282: 
 1283: =pod
 1284: 
 1285: =item * &viewport_geometry_js 
 1286: 
 1287: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1288: 
 1289: =cut
 1290: 
 1291: 
 1292: sub viewport_geometry_js { 
 1293:     return <<"GEOMETRY";
 1294: var Geometry = {};
 1295: function init_geometry() {
 1296:     if (Geometry.init) { return };
 1297:     Geometry.init=1;
 1298:     if (window.innerHeight) {
 1299:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1300:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1301:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1302:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1303:     }
 1304:     else if (document.documentElement && document.documentElement.clientHeight) {
 1305:         Geometry.getViewportHeight =
 1306:             function() { return document.documentElement.clientHeight; };
 1307:         Geometry.getViewportWidth =
 1308:             function() { return document.documentElement.clientWidth; };
 1309: 
 1310:         Geometry.getHorizontalScroll =
 1311:             function() { return document.documentElement.scrollLeft; };
 1312:         Geometry.getVerticalScroll =
 1313:             function() { return document.documentElement.scrollTop; };
 1314:     }
 1315:     else if (document.body.clientHeight) {
 1316:         Geometry.getViewportHeight =
 1317:             function() { return document.body.clientHeight; };
 1318:         Geometry.getViewportWidth =
 1319:             function() { return document.body.clientWidth; };
 1320:         Geometry.getHorizontalScroll =
 1321:             function() { return document.body.scrollLeft; };
 1322:         Geometry.getVerticalScroll =
 1323:             function() { return document.body.scrollTop; };
 1324:     }
 1325: }
 1326: 
 1327: GEOMETRY
 1328: }
 1329: 
 1330: =pod
 1331: 
 1332: =item * &viewport_size_js()
 1333: 
 1334: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1335: 
 1336: =cut
 1337: 
 1338: sub viewport_size_js {
 1339:     my $geometry = &viewport_geometry_js();
 1340:     return <<"DIMS";
 1341: 
 1342: $geometry
 1343: 
 1344: function getViewportDims(width,height) {
 1345:     init_geometry();
 1346:     width.value = Geometry.getViewportWidth();
 1347:     height.value = Geometry.getViewportHeight();
 1348:     return;
 1349: }
 1350: 
 1351: DIMS
 1352: }
 1353: 
 1354: =pod
 1355: 
 1356: =item * &resize_textarea_js()
 1357: 
 1358: emits the needed javascript to resize a textarea to be as big as possible
 1359: 
 1360: creates a function resize_textrea that takes two IDs first should be
 1361: the id of the element to resize, second should be the id of a div that
 1362: surrounds everything that comes after the textarea, this routine needs
 1363: to be attached to the <body> for the onload and onresize events.
 1364: 
 1365: =back
 1366: 
 1367: =cut
 1368: 
 1369: sub resize_textarea_js {
 1370:     my $geometry = &viewport_geometry_js();
 1371:     return <<"RESIZE";
 1372:     <script type="text/javascript">
 1373: $geometry
 1374: 
 1375: function getX(element) {
 1376:     var x = 0;
 1377:     while (element) {
 1378: 	x += element.offsetLeft;
 1379: 	element = element.offsetParent;
 1380:     }
 1381:     return x;
 1382: }
 1383: function getY(element) {
 1384:     var y = 0;
 1385:     while (element) {
 1386: 	y += element.offsetTop;
 1387: 	element = element.offsetParent;
 1388:     }
 1389:     return y;
 1390: }
 1391: 
 1392: 
 1393: function resize_textarea(textarea_id,bottom_id) {
 1394:     init_geometry();
 1395:     var textarea        = document.getElementById(textarea_id);
 1396:     //alert(textarea);
 1397: 
 1398:     var textarea_top    = getY(textarea);
 1399:     var textarea_height = textarea.offsetHeight;
 1400:     var bottom          = document.getElementById(bottom_id);
 1401:     var bottom_top      = getY(bottom);
 1402:     var bottom_height   = bottom.offsetHeight;
 1403:     var window_height   = Geometry.getViewportHeight();
 1404:     var fudge           = 23;
 1405:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1406:     if (new_height < 300) {
 1407: 	new_height = 300;
 1408:     }
 1409:     textarea.style.height=new_height+'px';
 1410: }
 1411: </script>
 1412: RESIZE
 1413: 
 1414: }
 1415: 
 1416: =pod
 1417: 
 1418: =head1 Excel and CSV file utility routines
 1419: 
 1420: =over 4
 1421: 
 1422: =cut
 1423: 
 1424: ###############################################################
 1425: ###############################################################
 1426: 
 1427: =pod
 1428: 
 1429: =item * &csv_translate($text) 
 1430: 
 1431: Translate $text to allow it to be output as a 'comma separated values' 
 1432: format.
 1433: 
 1434: =cut
 1435: 
 1436: ###############################################################
 1437: ###############################################################
 1438: sub csv_translate {
 1439:     my $text = shift;
 1440:     $text =~ s/\"/\"\"/g;
 1441:     $text =~ s/\n/ /g;
 1442:     return $text;
 1443: }
 1444: 
 1445: ###############################################################
 1446: ###############################################################
 1447: 
 1448: =pod
 1449: 
 1450: =item * &define_excel_formats()
 1451: 
 1452: Define some commonly used Excel cell formats.
 1453: 
 1454: Currently supported formats:
 1455: 
 1456: =over 4
 1457: 
 1458: =item header
 1459: 
 1460: =item bold
 1461: 
 1462: =item h1
 1463: 
 1464: =item h2
 1465: 
 1466: =item h3
 1467: 
 1468: =item h4
 1469: 
 1470: =item i
 1471: 
 1472: =item date
 1473: 
 1474: =back
 1475: 
 1476: Inputs: $workbook
 1477: 
 1478: Returns: $format, a hash reference.
 1479: 
 1480: =cut
 1481: 
 1482: ###############################################################
 1483: ###############################################################
 1484: sub define_excel_formats {
 1485:     my ($workbook) = @_;
 1486:     my $format;
 1487:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1488:                                                 bottom    => 1,
 1489:                                                 align     => 'center');
 1490:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1491:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1492:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1493:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1494:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1495:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1496:     $format->{'date'} = $workbook->add_format(num_format=>
 1497:                                             'mm/dd/yyyy hh:mm:ss');
 1498:     return $format;
 1499: }
 1500: 
 1501: ###############################################################
 1502: ###############################################################
 1503: 
 1504: =pod
 1505: 
 1506: =item * &create_workbook()
 1507: 
 1508: Create an Excel worksheet.  If it fails, output message on the
 1509: request object and return undefs.
 1510: 
 1511: Inputs: Apache request object
 1512: 
 1513: Returns (undef) on failure, 
 1514:     Excel worksheet object, scalar with filename, and formats 
 1515:     from &Apache::loncommon::define_excel_formats on success
 1516: 
 1517: =cut
 1518: 
 1519: ###############################################################
 1520: ###############################################################
 1521: sub create_workbook {
 1522:     my ($r) = @_;
 1523:         #
 1524:     # Create the excel spreadsheet
 1525:     my $filename = '/prtspool/'.
 1526:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1527:         time.'_'.rand(1000000000).'.xls';
 1528:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1529:     if (! defined($workbook)) {
 1530:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1531:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1532:                             "This error has been logged.  ".
 1533:                             "Please alert your LON-CAPA administrator").
 1534:                   '</p>');
 1535:         return (undef);
 1536:     }
 1537:     #
 1538:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1539:     #
 1540:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1541:     return ($workbook,$filename,$format);
 1542: }
 1543: 
 1544: ###############################################################
 1545: ###############################################################
 1546: 
 1547: =pod
 1548: 
 1549: =item * &create_text_file()
 1550: 
 1551: Create a file to write to and eventually make available to the user.
 1552: If file creation fails, outputs an error message on the request object and 
 1553: return undefs.
 1554: 
 1555: Inputs: Apache request object, and file suffix
 1556: 
 1557: Returns (undef) on failure, 
 1558:     Filehandle and filename on success.
 1559: 
 1560: =cut
 1561: 
 1562: ###############################################################
 1563: ###############################################################
 1564: sub create_text_file {
 1565:     my ($r,$suffix) = @_;
 1566:     if (! defined($suffix)) { $suffix = 'txt'; };
 1567:     my $fh;
 1568:     my $filename = '/prtspool/'.
 1569:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1570:         time.'_'.rand(1000000000).'.'.$suffix;
 1571:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1572:     if (! defined($fh)) {
 1573:         $r->log_error("Couldn't open $filename for output $!");
 1574:         $r->print(&mt('Problems occurred in creating the output file. '
 1575:                      .'This error has been logged. '
 1576:                      .'Please alert your LON-CAPA administrator.'));
 1577:     }
 1578:     return ($fh,$filename)
 1579: }
 1580: 
 1581: 
 1582: =pod 
 1583: 
 1584: =back
 1585: 
 1586: =cut
 1587: 
 1588: ###############################################################
 1589: ##        Home server <option> list generating code          ##
 1590: ###############################################################
 1591: 
 1592: # ------------------------------------------
 1593: 
 1594: sub domain_select {
 1595:     my ($name,$value,$multiple)=@_;
 1596:     my %domains=map { 
 1597: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1598:     } &Apache::lonnet::all_domains();
 1599:     if ($multiple) {
 1600: 	$domains{''}=&mt('Any domain');
 1601: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1602: 	return &multiple_select_form($name,$value,4,\%domains);
 1603:     } else {
 1604: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1605: 	return &select_form($name,$value,%domains);
 1606:     }
 1607: }
 1608: 
 1609: #-------------------------------------------
 1610: 
 1611: =pod
 1612: 
 1613: =head1 Routines for form select boxes
 1614: 
 1615: =over 4
 1616: 
 1617: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1618: 
 1619: Returns a string containing a <select> element int multiple mode
 1620: 
 1621: 
 1622: Args:
 1623:   $name - name of the <select> element
 1624:   $value - scalar or array ref of values that should already be selected
 1625:   $size - number of rows long the select element is
 1626:   $hash - the elements should be 'option' => 'shown text'
 1627:           (shown text should already have been &mt())
 1628:   $order - (optional) array ref of the order to show the elements in
 1629: 
 1630: =cut
 1631: 
 1632: #-------------------------------------------
 1633: sub multiple_select_form {
 1634:     my ($name,$value,$size,$hash,$order)=@_;
 1635:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1636:     my $output='';
 1637:     if (! defined($size)) {
 1638:         $size = 4;
 1639:         if (scalar(keys(%$hash))<4) {
 1640:             $size = scalar(keys(%$hash));
 1641:         }
 1642:     }
 1643:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1644:     my @order;
 1645:     if (ref($order) eq 'ARRAY')  {
 1646:         @order = @{$order};
 1647:     } else {
 1648:         @order = sort(keys(%$hash));
 1649:     }
 1650:     if (exists($$hash{'select_form_order'})) {
 1651:         @order = @{$$hash{'select_form_order'}};
 1652:     }
 1653:         
 1654:     foreach my $key (@order) {
 1655:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1656:         $output.='selected="selected" ' if ($selected{$key});
 1657:         $output.='>'.$hash->{$key}."</option>\n";
 1658:     }
 1659:     $output.="</select>\n";
 1660:     return $output;
 1661: }
 1662: 
 1663: #-------------------------------------------
 1664: 
 1665: =pod
 1666: 
 1667: =item * &select_form($defdom,$name,%hash)
 1668: 
 1669: Returns a string containing a <select name='$name' size='1'> form to 
 1670: allow a user to select options from a hash option_name => displayed text.  
 1671: See lonrights.pm for an example invocation and use.
 1672: 
 1673: =cut
 1674: 
 1675: #-------------------------------------------
 1676: sub select_form {
 1677:     my ($def,$name,%hash) = @_;
 1678:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1679:     my @keys;
 1680:     if (exists($hash{'select_form_order'})) {
 1681: 	@keys=@{$hash{'select_form_order'}};
 1682:     } else {
 1683: 	@keys=sort(keys(%hash));
 1684:     }
 1685:     foreach my $key (@keys) {
 1686:         $selectform.=
 1687: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1688:             ($key eq $def ? 'selected="selected" ' : '').
 1689:                 ">".&mt($hash{$key})."</option>\n";
 1690:     }
 1691:     $selectform.="</select>";
 1692:     return $selectform;
 1693: }
 1694: 
 1695: # For display filters
 1696: 
 1697: sub display_filter {
 1698:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1699:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1700:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1701: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1702: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1703: 	   '</label></span> <span class="LC_nobreak">'.
 1704:            &mt('Filter [_1]',
 1705: 	   &select_form($env{'form.displayfilter'},
 1706: 			'displayfilter',
 1707: 			('currentfolder' => 'Current folder/page',
 1708: 			 'containing' => 'Containing phrase',
 1709: 			 'none' => 'None'))).
 1710: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1711: }
 1712: 
 1713: sub gradeleveldescription {
 1714:     my $gradelevel=shift;
 1715:     my %gradelevels=(0 => 'Not specified',
 1716: 		     1 => 'Grade 1',
 1717: 		     2 => 'Grade 2',
 1718: 		     3 => 'Grade 3',
 1719: 		     4 => 'Grade 4',
 1720: 		     5 => 'Grade 5',
 1721: 		     6 => 'Grade 6',
 1722: 		     7 => 'Grade 7',
 1723: 		     8 => 'Grade 8',
 1724: 		     9 => 'Grade 9',
 1725: 		     10 => 'Grade 10',
 1726: 		     11 => 'Grade 11',
 1727: 		     12 => 'Grade 12',
 1728: 		     13 => 'Grade 13',
 1729: 		     14 => '100 Level',
 1730: 		     15 => '200 Level',
 1731: 		     16 => '300 Level',
 1732: 		     17 => '400 Level',
 1733: 		     18 => 'Graduate Level');
 1734:     return &mt($gradelevels{$gradelevel});
 1735: }
 1736: 
 1737: sub select_level_form {
 1738:     my ($deflevel,$name)=@_;
 1739:     unless ($deflevel) { $deflevel=0; }
 1740:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1741:     for (my $i=0; $i<=18; $i++) {
 1742:         $selectform.="<option value=\"$i\" ".
 1743:             ($i==$deflevel ? 'selected="selected" ' : '').
 1744:                 ">".&gradeleveldescription($i)."</option>\n";
 1745:     }
 1746:     $selectform.="</select>";
 1747:     return $selectform;
 1748: }
 1749: 
 1750: #-------------------------------------------
 1751: 
 1752: =pod
 1753: 
 1754: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1755: 
 1756: Returns a string containing a <select name='$name' size='1'> form to 
 1757: allow a user to select the domain to preform an operation in.  
 1758: See loncreateuser.pm for an example invocation and use.
 1759: 
 1760: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1761: selected");
 1762: 
 1763: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1764: 
 1765: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1766: 
 1767: =cut
 1768: 
 1769: #-------------------------------------------
 1770: sub select_dom_form {
 1771:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1772:     my $onchange;
 1773:     if ($autosubmit) {
 1774:         $onchange = ' onchange="this.form.submit()"';
 1775:     }
 1776:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1777:     if ($includeempty) { @domains=('',@domains); }
 1778:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1779:     foreach my $dom (@domains) {
 1780:         $selectdomain.="<option value=\"$dom\" ".
 1781:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1782:         if ($showdomdesc) {
 1783:             if ($dom ne '') {
 1784:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1785:                 if ($domdesc ne '') {
 1786:                     $selectdomain .= ' ('.$domdesc.')';
 1787:                 }
 1788:             } 
 1789:         }
 1790:         $selectdomain .= "</option>\n";
 1791:     }
 1792:     $selectdomain.="</select>";
 1793:     return $selectdomain;
 1794: }
 1795: 
 1796: #-------------------------------------------
 1797: 
 1798: =pod
 1799: 
 1800: =item * &home_server_form_item($domain,$name,$defaultflag)
 1801: 
 1802: input: 4 arguments (two required, two optional) - 
 1803:     $domain - domain of new user
 1804:     $name - name of form element
 1805:     $default - Value of 'default' causes a default item to be first 
 1806:                             option, and selected by default. 
 1807:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1808:                             if 1 server found, or default, if 0 found.
 1809: output: returns 2 items: 
 1810: (a) form element which contains either:
 1811:    (i) <select name="$name">
 1812:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1813:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1814:        </select>
 1815:        form item if there are multiple library servers in $domain, or
 1816:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1817:        if there is only one library server in $domain.
 1818: 
 1819: (b) number of library servers found.
 1820: 
 1821: See loncreateuser.pm for example of use.
 1822: 
 1823: =cut
 1824: 
 1825: #-------------------------------------------
 1826: sub home_server_form_item {
 1827:     my ($domain,$name,$default,$hide) = @_;
 1828:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1829:     my $result;
 1830:     my $numlib = keys(%servers);
 1831:     if ($numlib > 1) {
 1832:         $result .= '<select name="'.$name.'" />'."\n";
 1833:         if ($default) {
 1834:             $result .= '<option value="default" selected>'.&mt('default').
 1835:                        '</option>'."\n";
 1836:         }
 1837:         foreach my $hostid (sort(keys(%servers))) {
 1838:             $result.= '<option value="'.$hostid.'">'.
 1839: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1840:         }
 1841:         $result .= '</select>'."\n";
 1842:     } elsif ($numlib == 1) {
 1843:         my $hostid;
 1844:         foreach my $item (keys(%servers)) {
 1845:             $hostid = $item;
 1846:         }
 1847:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1848:                    $hostid.'" />';
 1849:                    if (!$hide) {
 1850:                        $result .= $hostid.' '.$servers{$hostid};
 1851:                    }
 1852:                    $result .= "\n";
 1853:     } elsif ($default) {
 1854:         $result .= '<input type="hidden" name="'.$name.
 1855:                    '" value="default" />';
 1856:                    if (!$hide) {
 1857:                        $result .= &mt('default');
 1858:                    }
 1859:                    $result .= "\n";
 1860:     }
 1861:     return ($result,$numlib);
 1862: }
 1863: 
 1864: =pod
 1865: 
 1866: =back 
 1867: 
 1868: =cut
 1869: 
 1870: ###############################################################
 1871: ##                  Decoding User Agent                      ##
 1872: ###############################################################
 1873: 
 1874: =pod
 1875: 
 1876: =head1 Decoding the User Agent
 1877: 
 1878: =over 4
 1879: 
 1880: =item * &decode_user_agent()
 1881: 
 1882: Inputs: $r
 1883: 
 1884: Outputs:
 1885: 
 1886: =over 4
 1887: 
 1888: =item * $httpbrowser
 1889: 
 1890: =item * $clientbrowser
 1891: 
 1892: =item * $clientversion
 1893: 
 1894: =item * $clientmathml
 1895: 
 1896: =item * $clientunicode
 1897: 
 1898: =item * $clientos
 1899: 
 1900: =back
 1901: 
 1902: =back 
 1903: 
 1904: =cut
 1905: 
 1906: ###############################################################
 1907: ###############################################################
 1908: sub decode_user_agent {
 1909:     my ($r)=@_;
 1910:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1911:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1912:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1913:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1914:     my $clientbrowser='unknown';
 1915:     my $clientversion='0';
 1916:     my $clientmathml='';
 1917:     my $clientunicode='0';
 1918:     for (my $i=0;$i<=$#browsertype;$i++) {
 1919:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1920: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1921: 	    $clientbrowser=$bname;
 1922:             $httpbrowser=~/$vreg/i;
 1923: 	    $clientversion=$1;
 1924:             $clientmathml=($clientversion>=$minv);
 1925:             $clientunicode=($clientversion>=$univ);
 1926: 	}
 1927:     }
 1928:     my $clientos='unknown';
 1929:     if (($httpbrowser=~/linux/i) ||
 1930:         ($httpbrowser=~/unix/i) ||
 1931:         ($httpbrowser=~/ux/i) ||
 1932:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1933:     if (($httpbrowser=~/vax/i) ||
 1934:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1935:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1936:     if (($httpbrowser=~/mac/i) ||
 1937:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1938:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1939:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1940:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1941:             $clientunicode,$clientos,);
 1942: }
 1943: 
 1944: ###############################################################
 1945: ##    Authentication changing form generation subroutines    ##
 1946: ###############################################################
 1947: ##
 1948: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1949: ## hash, and have reasonable default values.
 1950: ##
 1951: ##    formname = the name given in the <form> tag.
 1952: #-------------------------------------------
 1953: 
 1954: =pod
 1955: 
 1956: =head1 Authentication Routines
 1957: 
 1958: =over 4
 1959: 
 1960: =item * &authform_xxxxxx()
 1961: 
 1962: The authform_xxxxxx subroutines provide javascript and html forms which 
 1963: handle some of the conveniences required for authentication forms.  
 1964: This is not an optimal method, but it works.  
 1965: 
 1966: =over 4
 1967: 
 1968: =item * authform_header
 1969: 
 1970: =item * authform_authorwarning
 1971: 
 1972: =item * authform_nochange
 1973: 
 1974: =item * authform_kerberos
 1975: 
 1976: =item * authform_internal
 1977: 
 1978: =item * authform_filesystem
 1979: 
 1980: =back
 1981: 
 1982: See loncreateuser.pm for invocation and use examples.
 1983: 
 1984: =cut
 1985: 
 1986: #-------------------------------------------
 1987: sub authform_header{  
 1988:     my %in = (
 1989:         formname => 'cu',
 1990:         kerb_def_dom => '',
 1991:         @_,
 1992:     );
 1993:     $in{'formname'} = 'document.' . $in{'formname'};
 1994:     my $result='';
 1995: 
 1996: #---------------------------------------------- Code for upper case translation
 1997:     my $Javascript_toUpperCase;
 1998:     unless ($in{kerb_def_dom}) {
 1999:         $Javascript_toUpperCase =<<"END";
 2000:         switch (choice) {
 2001:            case 'krb': currentform.elements[choicearg].value =
 2002:                currentform.elements[choicearg].value.toUpperCase();
 2003:                break;
 2004:            default:
 2005:         }
 2006: END
 2007:     } else {
 2008:         $Javascript_toUpperCase = "";
 2009:     }
 2010: 
 2011:     my $radioval = "'nochange'";
 2012:     if (defined($in{'curr_authtype'})) {
 2013:         if ($in{'curr_authtype'} ne '') {
 2014:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2015:         }
 2016:     }
 2017:     my $argfield = 'null';
 2018:     if (defined($in{'mode'})) {
 2019:         if ($in{'mode'} eq 'modifycourse')  {
 2020:             if (defined($in{'curr_autharg'})) {
 2021:                 if ($in{'curr_autharg'} ne '') {
 2022:                     $argfield = "'$in{'curr_autharg'}'";
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027: 
 2028:     $result.=<<"END";
 2029: var current = new Object();
 2030: current.radiovalue = $radioval;
 2031: current.argfield = $argfield;
 2032: 
 2033: function changed_radio(choice,currentform) {
 2034:     var choicearg = choice + 'arg';
 2035:     // If a radio button in changed, we need to change the argfield
 2036:     if (current.radiovalue != choice) {
 2037:         current.radiovalue = choice;
 2038:         if (current.argfield != null) {
 2039:             currentform.elements[current.argfield].value = '';
 2040:         }
 2041:         if (choice == 'nochange') {
 2042:             current.argfield = null;
 2043:         } else {
 2044:             current.argfield = choicearg;
 2045:             switch(choice) {
 2046:                 case 'krb': 
 2047:                     currentform.elements[current.argfield].value = 
 2048:                         "$in{'kerb_def_dom'}";
 2049:                 break;
 2050:               default:
 2051:                 break;
 2052:             }
 2053:         }
 2054:     }
 2055:     return;
 2056: }
 2057: 
 2058: function changed_text(choice,currentform) {
 2059:     var choicearg = choice + 'arg';
 2060:     if (currentform.elements[choicearg].value !='') {
 2061:         $Javascript_toUpperCase
 2062:         // clear old field
 2063:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2064:             currentform.elements[current.argfield].value = '';
 2065:         }
 2066:         current.argfield = choicearg;
 2067:     }
 2068:     set_auth_radio_buttons(choice,currentform);
 2069:     return;
 2070: }
 2071: 
 2072: function set_auth_radio_buttons(newvalue,currentform) {
 2073:     var i=0;
 2074:     while (i < currentform.login.length) {
 2075:         if (currentform.login[i].value == newvalue) { break; }
 2076:         i++;
 2077:     }
 2078:     if (i == currentform.login.length) {
 2079:         return;
 2080:     }
 2081:     current.radiovalue = newvalue;
 2082:     currentform.login[i].checked = true;
 2083:     return;
 2084: }
 2085: END
 2086:     return $result;
 2087: }
 2088: 
 2089: sub authform_authorwarning{
 2090:     my $result='';
 2091:     $result='<i>'.
 2092:         &mt('As a general rule, only authors or co-authors should be '.
 2093:             'filesystem authenticated '.
 2094:             '(which allows access to the server filesystem).')."</i>\n";
 2095:     return $result;
 2096: }
 2097: 
 2098: sub authform_nochange{  
 2099:     my %in = (
 2100:               formname => 'document.cu',
 2101:               kerb_def_dom => 'MSU.EDU',
 2102:               @_,
 2103:           );
 2104:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2105:     my $result;
 2106:     if (keys(%can_assign) == 0) {
 2107:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2108:     } else {
 2109:         $result = '<label>'.&mt('[_1] Do not change login data',
 2110:                   '<input type="radio" name="login" value="nochange" '.
 2111:                   'checked="checked" onclick="'.
 2112:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2113: 	    '</label>';
 2114:     }
 2115:     return $result;
 2116: }
 2117: 
 2118: sub authform_kerberos {
 2119:     my %in = (
 2120:               formname => 'document.cu',
 2121:               kerb_def_dom => 'MSU.EDU',
 2122:               kerb_def_auth => 'krb4',
 2123:               @_,
 2124:               );
 2125:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2126:         $autharg,$jscall);
 2127:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2128:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2129:        $check5 = ' checked="checked"';
 2130:     } else {
 2131:        $check4 = ' checked="checked"';
 2132:     }
 2133:     $krbarg = $in{'kerb_def_dom'};
 2134:     if (defined($in{'curr_authtype'})) {
 2135:         if ($in{'curr_authtype'} eq 'krb') {
 2136:             $krbcheck = ' checked="checked"';
 2137:             if (defined($in{'mode'})) {
 2138:                 if ($in{'mode'} eq 'modifyuser') {
 2139:                     $krbcheck = '';
 2140:                 }
 2141:             }
 2142:             if (defined($in{'curr_kerb_ver'})) {
 2143:                 if ($in{'curr_krb_ver'} eq '5') {
 2144:                     $check5 = ' checked="checked"';
 2145:                     $check4 = '';
 2146:                 } else {
 2147:                     $check4 = ' checked="checked"';
 2148:                     $check5 = '';
 2149:                 }
 2150:             }
 2151:             if (defined($in{'curr_autharg'})) {
 2152:                 $krbarg = $in{'curr_autharg'};
 2153:             }
 2154:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2155:                 if (defined($in{'curr_autharg'})) {
 2156:                     $result = 
 2157:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2158:         $in{'curr_autharg'},$krbver);
 2159:                 } else {
 2160:                     $result =
 2161:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2162:                 }
 2163:                 return $result; 
 2164:             }
 2165:         }
 2166:     } else {
 2167:         if ($authnum == 1) {
 2168:             $authtype = '<input type="hidden" name="login" value="krb">';
 2169:         }
 2170:     }
 2171:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2172:         return;
 2173:     } elsif ($authtype eq '') {
 2174:         if (defined($in{'mode'})) {
 2175:             if ($in{'mode'} eq 'modifycourse') {
 2176:                 if ($authnum == 1) {
 2177:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2178:                 }
 2179:             }
 2180:         }
 2181:     }
 2182:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2183:     if ($authtype eq '') {
 2184:         $authtype = '<input type="radio" name="login" value="krb" '.
 2185:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2186:                     $krbcheck.' />';
 2187:     }
 2188:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2189:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2190:          $in{'curr_authtype'} eq 'krb5') ||
 2191:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2192:          $in{'curr_authtype'} eq 'krb4')) {
 2193:         $result .= &mt
 2194:         ('[_1] Kerberos authenticated with domain [_2] '.
 2195:          '[_3] Version 4 [_4] Version 5 [_5]',
 2196:          '<label>'.$authtype,
 2197:          '</label><input type="text" size="10" name="krbarg" '.
 2198:              'value="'.$krbarg.'" '.
 2199:              'onchange="'.$jscall.'" />',
 2200:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2201:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2202: 	 '</label>');
 2203:     } elsif ($can_assign{'krb4'}) {
 2204:         $result .= &mt
 2205:         ('[_1] Kerberos authenticated with domain [_2] '.
 2206:          '[_3] Version 4 [_4]',
 2207:          '<label>'.$authtype,
 2208:          '</label><input type="text" size="10" name="krbarg" '.
 2209:              'value="'.$krbarg.'" '.
 2210:              'onchange="'.$jscall.'" />',
 2211:          '<label><input type="hidden" name="krbver" value="4" />',
 2212:          '</label>');
 2213:     } elsif ($can_assign{'krb5'}) {
 2214:         $result .= &mt
 2215:         ('[_1] Kerberos authenticated with domain [_2] '.
 2216:          '[_3] Version 5 [_4]',
 2217:          '<label>'.$authtype,
 2218:          '</label><input type="text" size="10" name="krbarg" '.
 2219:              'value="'.$krbarg.'" '.
 2220:              'onchange="'.$jscall.'" />',
 2221:          '<label><input type="hidden" name="krbver" value="5" />',
 2222:          '</label>');
 2223:     }
 2224:     return $result;
 2225: }
 2226: 
 2227: sub authform_internal{  
 2228:     my %in = (
 2229:                 formname => 'document.cu',
 2230:                 kerb_def_dom => 'MSU.EDU',
 2231:                 @_,
 2232:                 );
 2233:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2234:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2235:     if (defined($in{'curr_authtype'})) {
 2236:         if ($in{'curr_authtype'} eq 'int') {
 2237:             if ($can_assign{'int'}) {
 2238:                 $intcheck = 'checked="checked" ';
 2239:                 if (defined($in{'mode'})) {
 2240:                     if ($in{'mode'} eq 'modifyuser') {
 2241:                         $intcheck = '';
 2242:                     }
 2243:                 }
 2244:                 if (defined($in{'curr_autharg'})) {
 2245:                     $intarg = $in{'curr_autharg'};
 2246:                 }
 2247:             } else {
 2248:                 $result = &mt('Currently internally authenticated.');
 2249:                 return $result;
 2250:             }
 2251:         }
 2252:     } else {
 2253:         if ($authnum == 1) {
 2254:             $authtype = '<input type="hidden" name="login" value="int">';
 2255:         }
 2256:     }
 2257:     if (!$can_assign{'int'}) {
 2258:         return;
 2259:     } elsif ($authtype eq '') {
 2260:         if (defined($in{'mode'})) {
 2261:             if ($in{'mode'} eq 'modifycourse') {
 2262:                 if ($authnum == 1) {
 2263:                     $authtype = '<input type="hidden" name="login" value="int">';
 2264:                 }
 2265:             }
 2266:         }
 2267:     }
 2268:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2269:     if ($authtype eq '') {
 2270:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2271:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2272:     }
 2273:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2274:                $intarg.'" onchange="'.$jscall.'" />';
 2275:     $result = &mt
 2276:         ('[_1] Internally authenticated (with initial password [_2])',
 2277:          '<label>'.$authtype,'</label>'.$autharg);
 2278:     $result.="<label><input type=\"checkbox\" name=\"visible\" onClick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2279:     return $result;
 2280: }
 2281: 
 2282: sub authform_local{  
 2283:     my %in = (
 2284:               formname => 'document.cu',
 2285:               kerb_def_dom => 'MSU.EDU',
 2286:               @_,
 2287:               );
 2288:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2289:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2290:     if (defined($in{'curr_authtype'})) {
 2291:         if ($in{'curr_authtype'} eq 'loc') {
 2292:             if ($can_assign{'loc'}) {
 2293:                 $loccheck = 'checked="checked" ';
 2294:                 if (defined($in{'mode'})) {
 2295:                     if ($in{'mode'} eq 'modifyuser') {
 2296:                         $loccheck = '';
 2297:                     }
 2298:                 }
 2299:                 if (defined($in{'curr_autharg'})) {
 2300:                     $locarg = $in{'curr_autharg'};
 2301:                 }
 2302:             } else {
 2303:                 $result = &mt('Currently using local (institutional) authentication.');
 2304:                 return $result;
 2305:             }
 2306:         }
 2307:     } else {
 2308:         if ($authnum == 1) {
 2309:             $authtype = '<input type="hidden" name="login" value="loc">';
 2310:         }
 2311:     }
 2312:     if (!$can_assign{'loc'}) {
 2313:         return;
 2314:     } elsif ($authtype eq '') {
 2315:         if (defined($in{'mode'})) {
 2316:             if ($in{'mode'} eq 'modifycourse') {
 2317:                 if ($authnum == 1) {
 2318:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2319:                 }
 2320:             }
 2321:         }
 2322:     }
 2323:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2324:     if ($authtype eq '') {
 2325:         $authtype = '<input type="radio" name="login" value="loc" '.
 2326:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2327:                     $jscall.'" />';
 2328:     }
 2329:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2330:                $locarg.'" onchange="'.$jscall.'" />';
 2331:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2332:                   '<label>'.$authtype,'</label>'.$autharg);
 2333:     return $result;
 2334: }
 2335: 
 2336: sub authform_filesystem{  
 2337:     my %in = (
 2338:               formname => 'document.cu',
 2339:               kerb_def_dom => 'MSU.EDU',
 2340:               @_,
 2341:               );
 2342:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2343:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2344:     if (defined($in{'curr_authtype'})) {
 2345:         if ($in{'curr_authtype'} eq 'fsys') {
 2346:             if ($can_assign{'fsys'}) {
 2347:                 $fsyscheck = 'checked="checked" ';
 2348:                 if (defined($in{'mode'})) {
 2349:                     if ($in{'mode'} eq 'modifyuser') {
 2350:                         $fsyscheck = '';
 2351:                     }
 2352:                 }
 2353:             } else {
 2354:                 $result = &mt('Currently Filesystem Authenticated.');
 2355:                 return $result;
 2356:             }           
 2357:         }
 2358:     } else {
 2359:         if ($authnum == 1) {
 2360:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2361:         }
 2362:     }
 2363:     if (!$can_assign{'fsys'}) {
 2364:         return;
 2365:     } elsif ($authtype eq '') {
 2366:         if (defined($in{'mode'})) {
 2367:             if ($in{'mode'} eq 'modifycourse') {
 2368:                 if ($authnum == 1) {
 2369:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2370:                 }
 2371:             }
 2372:         }
 2373:     }
 2374:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2375:     if ($authtype eq '') {
 2376:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2377:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2378:                     $jscall.'" />';
 2379:     }
 2380:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2381:                ' onchange="'.$jscall.'" />';
 2382:     $result = &mt
 2383:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2384:          '<label><input type="radio" name="login" value="fsys" '.
 2385:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2386:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2387:                   'onchange="'.$jscall.'" />');
 2388:     return $result;
 2389: }
 2390: 
 2391: sub get_assignable_auth {
 2392:     my ($dom) = @_;
 2393:     if ($dom eq '') {
 2394:         $dom = $env{'request.role.domain'};
 2395:     }
 2396:     my %can_assign = (
 2397:                           krb4 => 1,
 2398:                           krb5 => 1,
 2399:                           int  => 1,
 2400:                           loc  => 1,
 2401:                      );
 2402:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2403:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2404:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2405:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2406:             my $context;
 2407:             if ($env{'request.role'} =~ /^au/) {
 2408:                 $context = 'author';
 2409:             } elsif ($env{'request.role'} =~ /^dc/) {
 2410:                 $context = 'domain';
 2411:             } elsif ($env{'request.course.id'}) {
 2412:                 $context = 'course';
 2413:             }
 2414:             if ($context) {
 2415:                 if (ref($authhash->{$context}) eq 'HASH') {
 2416:                    %can_assign = %{$authhash->{$context}}; 
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     my $authnum = 0;
 2422:     foreach my $key (keys(%can_assign)) {
 2423:         if ($can_assign{$key}) {
 2424:             $authnum ++;
 2425:         }
 2426:     }
 2427:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2428:         $authnum --;
 2429:     }
 2430:     return ($authnum,%can_assign);
 2431: }
 2432: 
 2433: ###############################################################
 2434: ##    Get Kerberos Defaults for Domain                 ##
 2435: ###############################################################
 2436: ##
 2437: ## Returns default kerberos version and an associated argument
 2438: ## as listed in file domain.tab. If not listed, provides
 2439: ## appropriate default domain and kerberos version.
 2440: ##
 2441: #-------------------------------------------
 2442: 
 2443: =pod
 2444: 
 2445: =item * &get_kerberos_defaults()
 2446: 
 2447: get_kerberos_defaults($target_domain) returns the default kerberos
 2448: version and domain. If not found, it defaults to version 4 and the 
 2449: domain of the server.
 2450: 
 2451: =over 4
 2452: 
 2453: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2454: 
 2455: =back
 2456: 
 2457: =back
 2458: 
 2459: =cut
 2460: 
 2461: #-------------------------------------------
 2462: sub get_kerberos_defaults {
 2463:     my $domain=shift;
 2464:     my ($krbdef,$krbdefdom);
 2465:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2466:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2467:         $krbdef = $domdefaults{'auth_def'};
 2468:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2469:     } else {
 2470:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2471:         my $krbdefdom=$1;
 2472:         $krbdefdom=~tr/a-z/A-Z/;
 2473:         $krbdef = "krb4";
 2474:     }
 2475:     return ($krbdef,$krbdefdom);
 2476: }
 2477: 
 2478: 
 2479: ###############################################################
 2480: ##                Thesaurus Functions                        ##
 2481: ###############################################################
 2482: 
 2483: =pod
 2484: 
 2485: =head1 Thesaurus Functions
 2486: 
 2487: =over 4
 2488: 
 2489: =item * &initialize_keywords()
 2490: 
 2491: Initializes the package variable %Keywords if it is empty.  Uses the
 2492: package variable $thesaurus_db_file.
 2493: 
 2494: =cut
 2495: 
 2496: ###################################################
 2497: 
 2498: sub initialize_keywords {
 2499:     return 1 if (scalar keys(%Keywords));
 2500:     # If we are here, %Keywords is empty, so fill it up
 2501:     #   Make sure the file we need exists...
 2502:     if (! -e $thesaurus_db_file) {
 2503:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2504:                                  " failed because it does not exist");
 2505:         return 0;
 2506:     }
 2507:     #   Set up the hash as a database
 2508:     my %thesaurus_db;
 2509:     if (! tie(%thesaurus_db,'GDBM_File',
 2510:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2511:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2512:                                  $thesaurus_db_file);
 2513:         return 0;
 2514:     } 
 2515:     #  Get the average number of appearances of a word.
 2516:     my $avecount = $thesaurus_db{'average.count'};
 2517:     #  Put keywords (those that appear > average) into %Keywords
 2518:     while (my ($word,$data)=each (%thesaurus_db)) {
 2519:         my ($count,undef) = split /:/,$data;
 2520:         $Keywords{$word}++ if ($count > $avecount);
 2521:     }
 2522:     untie %thesaurus_db;
 2523:     # Remove special values from %Keywords.
 2524:     foreach my $value ('total.count','average.count') {
 2525:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2526:   }
 2527:     return 1;
 2528: }
 2529: 
 2530: ###################################################
 2531: 
 2532: =pod
 2533: 
 2534: =item * &keyword($word)
 2535: 
 2536: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2537: than the average number of times in the thesaurus database.  Calls 
 2538: &initialize_keywords
 2539: 
 2540: =cut
 2541: 
 2542: ###################################################
 2543: 
 2544: sub keyword {
 2545:     return if (!&initialize_keywords());
 2546:     my $word=lc(shift());
 2547:     $word=~s/\W//g;
 2548:     return exists($Keywords{$word});
 2549: }
 2550: 
 2551: ###############################################################
 2552: 
 2553: =pod 
 2554: 
 2555: =item * &get_related_words()
 2556: 
 2557: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2558: an array of words.  If the keyword is not in the thesaurus, an empty array
 2559: will be returned.  The order of the words returned is determined by the
 2560: database which holds them.
 2561: 
 2562: Uses global $thesaurus_db_file.
 2563: 
 2564: =cut
 2565: 
 2566: ###############################################################
 2567: sub get_related_words {
 2568:     my $keyword = shift;
 2569:     my %thesaurus_db;
 2570:     if (! -e $thesaurus_db_file) {
 2571:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2572:                                  "failed because the file does not exist");
 2573:         return ();
 2574:     }
 2575:     if (! tie(%thesaurus_db,'GDBM_File',
 2576:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2577:         return ();
 2578:     } 
 2579:     my @Words=();
 2580:     my $count=0;
 2581:     if (exists($thesaurus_db{$keyword})) {
 2582: 	# The first element is the number of times
 2583: 	# the word appears.  We do not need it now.
 2584: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2585: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2586: 	my $threshold=$mostfrequentcount/10;
 2587:         foreach my $possibleword (@RelatedWords) {
 2588:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2589:             if ($wordcount>$threshold) {
 2590: 		push(@Words,$word);
 2591:                 $count++;
 2592:                 if ($count>10) { last; }
 2593: 	    }
 2594:         }
 2595:     }
 2596:     untie %thesaurus_db;
 2597:     return @Words;
 2598: }
 2599: 
 2600: =pod
 2601: 
 2602: =back
 2603: 
 2604: =cut
 2605: 
 2606: # -------------------------------------------------------------- Plaintext name
 2607: =pod
 2608: 
 2609: =head1 User Name Functions
 2610: 
 2611: =over 4
 2612: 
 2613: =item * &plainname($uname,$udom,$first)
 2614: 
 2615: Takes a users logon name and returns it as a string in
 2616: "first middle last generation" form 
 2617: if $first is set to 'lastname' then it returns it as
 2618: 'lastname generation, firstname middlename' if their is a lastname
 2619: 
 2620: =cut
 2621: 
 2622: 
 2623: ###############################################################
 2624: sub plainname {
 2625:     my ($uname,$udom,$first)=@_;
 2626:     return if (!defined($uname) || !defined($udom));
 2627:     my %names=&getnames($uname,$udom);
 2628:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2629: 					  $names{'middlename'},
 2630: 					  $names{'lastname'},
 2631: 					  $names{'generation'},$first);
 2632:     $name=~s/^\s+//;
 2633:     $name=~s/\s+$//;
 2634:     $name=~s/\s+/ /g;
 2635:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2636:     return $name;
 2637: }
 2638: 
 2639: # -------------------------------------------------------------------- Nickname
 2640: =pod
 2641: 
 2642: =item * &nickname($uname,$udom)
 2643: 
 2644: Gets a users name and returns it as a string as
 2645: 
 2646: "&quot;nickname&quot;"
 2647: 
 2648: if the user has a nickname or
 2649: 
 2650: "first middle last generation"
 2651: 
 2652: if the user does not
 2653: 
 2654: =cut
 2655: 
 2656: sub nickname {
 2657:     my ($uname,$udom)=@_;
 2658:     return if (!defined($uname) || !defined($udom));
 2659:     my %names=&getnames($uname,$udom);
 2660:     my $name=$names{'nickname'};
 2661:     if ($name) {
 2662:        $name='&quot;'.$name.'&quot;'; 
 2663:     } else {
 2664:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2665: 	     $names{'lastname'}.' '.$names{'generation'};
 2666:        $name=~s/\s+$//;
 2667:        $name=~s/\s+/ /g;
 2668:     }
 2669:     return $name;
 2670: }
 2671: 
 2672: sub getnames {
 2673:     my ($uname,$udom)=@_;
 2674:     return if (!defined($uname) || !defined($udom));
 2675:     if ($udom eq 'public' && $uname eq 'public') {
 2676: 	return ('lastname' => &mt('Public'));
 2677:     }
 2678:     my $id=$uname.':'.$udom;
 2679:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2680:     if ($cached) {
 2681: 	return %{$names};
 2682:     } else {
 2683: 	my %loadnames=&Apache::lonnet::get('environment',
 2684:                     ['firstname','middlename','lastname','generation','nickname'],
 2685: 					 $udom,$uname);
 2686: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2687: 	return %loadnames;
 2688:     }
 2689: }
 2690: 
 2691: # -------------------------------------------------------------------- getemails
 2692: 
 2693: =pod
 2694: 
 2695: =item * &getemails($uname,$udom)
 2696: 
 2697: Gets a user's email information and returns it as a hash with keys:
 2698: notification, critnotification, permanentemail
 2699: 
 2700: For notification and critnotification, values are comma-separated lists 
 2701: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2702:  
 2703: 
 2704: =cut
 2705: 
 2706: 
 2707: sub getemails {
 2708:     my ($uname,$udom)=@_;
 2709:     if ($udom eq 'public' && $uname eq 'public') {
 2710: 	return;
 2711:     }
 2712:     if (!$udom) { $udom=$env{'user.domain'}; }
 2713:     if (!$uname) { $uname=$env{'user.name'}; }
 2714:     my $id=$uname.':'.$udom;
 2715:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2716:     if ($cached) {
 2717: 	return %{$names};
 2718:     } else {
 2719: 	my %loadnames=&Apache::lonnet::get('environment',
 2720:                     			   ['notification','critnotification',
 2721: 					    'permanentemail'],
 2722: 					   $udom,$uname);
 2723: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2724: 	return %loadnames;
 2725:     }
 2726: }
 2727: 
 2728: sub flush_email_cache {
 2729:     my ($uname,$udom)=@_;
 2730:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2731:     if (!$uname) { $uname=$env{'user.name'};   }
 2732:     return if ($udom eq 'public' && $uname eq 'public');
 2733:     my $id=$uname.':'.$udom;
 2734:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2735: }
 2736: 
 2737: # -------------------------------------------------------------------- getlangs
 2738: 
 2739: =pod
 2740: 
 2741: =item * &getlangs($uname,$udom)
 2742: 
 2743: Gets a user's language preference and returns it as a hash with key:
 2744: language.
 2745: 
 2746: =cut
 2747: 
 2748: 
 2749: sub getlangs {
 2750:     my ($uname,$udom) = @_;
 2751:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2752:     if (!$uname) { $uname=$env{'user.name'};   }
 2753:     my $id=$uname.':'.$udom;
 2754:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2755:     if ($cached) {
 2756:         return %{$langs};
 2757:     } else {
 2758:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2759:                                            $udom,$uname);
 2760:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2761:         return %loadlangs;
 2762:     }
 2763: }
 2764: 
 2765: sub flush_langs_cache {
 2766:     my ($uname,$udom)=@_;
 2767:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2768:     if (!$uname) { $uname=$env{'user.name'};   }
 2769:     return if ($udom eq 'public' && $uname eq 'public');
 2770:     my $id=$uname.':'.$udom;
 2771:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2772: }
 2773: 
 2774: # ------------------------------------------------------------------ Screenname
 2775: 
 2776: =pod
 2777: 
 2778: =item * &screenname($uname,$udom)
 2779: 
 2780: Gets a users screenname and returns it as a string
 2781: 
 2782: =cut
 2783: 
 2784: sub screenname {
 2785:     my ($uname,$udom)=@_;
 2786:     if ($uname eq $env{'user.name'} &&
 2787: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2788:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2789:     return $names{'screenname'};
 2790: }
 2791: 
 2792: 
 2793: # ------------------------------------------------------------- Message Wrapper
 2794: 
 2795: sub messagewrapper {
 2796:     my ($link,$username,$domain,$subject,$text)=@_;
 2797:     return 
 2798:         '<a href="/adm/email?compose=individual&amp;'.
 2799:         'recname='.$username.'&amp;recdom='.$domain.
 2800: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2801:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2802: }
 2803: # --------------------------------------------------------------- Notes Wrapper
 2804: 
 2805: sub noteswrapper {
 2806:     my ($link,$un,$do)=@_;
 2807:     return 
 2808: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2809: }
 2810: # ------------------------------------------------------------- Aboutme Wrapper
 2811: 
 2812: sub aboutmewrapper {
 2813:     my ($link,$username,$domain,$target)=@_;
 2814:     if (!defined($username)  && !defined($domain)) {
 2815:         return;
 2816:     }
 2817:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2818: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2819: }
 2820: 
 2821: # ------------------------------------------------------------ Syllabus Wrapper
 2822: 
 2823: 
 2824: sub syllabuswrapper {
 2825:     my ($linktext,$coursedir,$domain)=@_;
 2826:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2827: }
 2828: 
 2829: sub track_student_link {
 2830:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2831:     my $link ="/adm/trackstudent?";
 2832:     my $title = 'View recent activity';
 2833:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2834:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2835:         $link .= "selected_student=$sname:$sdom";
 2836:         $title .= ' of this student';
 2837:     } 
 2838:     if (defined($target) && $target !~ /^\s*$/) {
 2839:         $target = qq{target="$target"};
 2840:     } else {
 2841:         $target = '';
 2842:     }
 2843:     if ($start) { $link.='&amp;start='.$start; }
 2844:     $title = &mt($title);
 2845:     $linktext = &mt($linktext);
 2846:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2847: 	&help_open_topic('View_recent_activity');
 2848: }
 2849: 
 2850: # ===================================================== Display a student photo
 2851: 
 2852: 
 2853: sub student_image_tag {
 2854:     my ($domain,$user)=@_;
 2855:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2856:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2857: 	return '<img src="'.$imgsrc.'" align="right" />';
 2858:     } else {
 2859: 	return '';
 2860:     }
 2861: }
 2862: 
 2863: =pod
 2864: 
 2865: =back
 2866: 
 2867: =head1 Access .tab File Data
 2868: 
 2869: =over 4
 2870: 
 2871: =item * &languageids() 
 2872: 
 2873: returns list of all language ids
 2874: 
 2875: =cut
 2876: 
 2877: sub languageids {
 2878:     return sort(keys(%language));
 2879: }
 2880: 
 2881: =pod
 2882: 
 2883: =item * &languagedescription() 
 2884: 
 2885: returns description of a specified language id
 2886: 
 2887: =cut
 2888: 
 2889: sub languagedescription {
 2890:     my $code=shift;
 2891:     return  ($supported_language{$code}?'* ':'').
 2892:             $language{$code}.
 2893: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2894: }
 2895: 
 2896: sub plainlanguagedescription {
 2897:     my $code=shift;
 2898:     return $language{$code};
 2899: }
 2900: 
 2901: sub supportedlanguagecode {
 2902:     my $code=shift;
 2903:     return $supported_language{$code};
 2904: }
 2905: 
 2906: =pod
 2907: 
 2908: =item * &copyrightids() 
 2909: 
 2910: returns list of all copyrights
 2911: 
 2912: =cut
 2913: 
 2914: sub copyrightids {
 2915:     return sort(keys(%cprtag));
 2916: }
 2917: 
 2918: =pod
 2919: 
 2920: =item * &copyrightdescription() 
 2921: 
 2922: returns description of a specified copyright id
 2923: 
 2924: =cut
 2925: 
 2926: sub copyrightdescription {
 2927:     return &mt($cprtag{shift(@_)});
 2928: }
 2929: 
 2930: =pod
 2931: 
 2932: =item * &source_copyrightids() 
 2933: 
 2934: returns list of all source copyrights
 2935: 
 2936: =cut
 2937: 
 2938: sub source_copyrightids {
 2939:     return sort(keys(%scprtag));
 2940: }
 2941: 
 2942: =pod
 2943: 
 2944: =item * &source_copyrightdescription() 
 2945: 
 2946: returns description of a specified source copyright id
 2947: 
 2948: =cut
 2949: 
 2950: sub source_copyrightdescription {
 2951:     return &mt($scprtag{shift(@_)});
 2952: }
 2953: 
 2954: =pod
 2955: 
 2956: =item * &filecategories() 
 2957: 
 2958: returns list of all file categories
 2959: 
 2960: =cut
 2961: 
 2962: sub filecategories {
 2963:     return sort(keys(%category_extensions));
 2964: }
 2965: 
 2966: =pod
 2967: 
 2968: =item * &filecategorytypes() 
 2969: 
 2970: returns list of file types belonging to a given file
 2971: category
 2972: 
 2973: =cut
 2974: 
 2975: sub filecategorytypes {
 2976:     my ($cat) = @_;
 2977:     return @{$category_extensions{lc($cat)}};
 2978: }
 2979: 
 2980: =pod
 2981: 
 2982: =item * &fileembstyle() 
 2983: 
 2984: returns embedding style for a specified file type
 2985: 
 2986: =cut
 2987: 
 2988: sub fileembstyle {
 2989:     return $fe{lc(shift(@_))};
 2990: }
 2991: 
 2992: sub filemimetype {
 2993:     return $fm{lc(shift(@_))};
 2994: }
 2995: 
 2996: 
 2997: sub filecategoryselect {
 2998:     my ($name,$value)=@_;
 2999:     return &select_form($value,$name,
 3000: 			'' => &mt('Any category'),
 3001: 			map { $_,$_ } sort(keys(%category_extensions)));
 3002: }
 3003: 
 3004: =pod
 3005: 
 3006: =item * &filedescription() 
 3007: 
 3008: returns description for a specified file type
 3009: 
 3010: =cut
 3011: 
 3012: sub filedescription {
 3013:     my $file_description = $fd{lc(shift())};
 3014:     $file_description =~ s:([\[\]]):~$1:g;
 3015:     return &mt($file_description);
 3016: }
 3017: 
 3018: =pod
 3019: 
 3020: =item * &filedescriptionex() 
 3021: 
 3022: returns description for a specified file type with
 3023: extra formatting
 3024: 
 3025: =cut
 3026: 
 3027: sub filedescriptionex {
 3028:     my $ex=shift;
 3029:     my $file_description = $fd{lc($ex)};
 3030:     $file_description =~ s:([\[\]]):~$1:g;
 3031:     return '.'.$ex.' '.&mt($file_description);
 3032: }
 3033: 
 3034: # End of .tab access
 3035: =pod
 3036: 
 3037: =back
 3038: 
 3039: =cut
 3040: 
 3041: # ------------------------------------------------------------------ File Types
 3042: sub fileextensions {
 3043:     return sort(keys(%fe));
 3044: }
 3045: 
 3046: # ----------------------------------------------------------- Display Languages
 3047: # returns a hash with all desired display languages
 3048: #
 3049: 
 3050: sub display_languages {
 3051:     my %languages=();
 3052:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3053: 	$languages{$lang}=1;
 3054:     }
 3055:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3056:     if ($env{'form.displaylanguage'}) {
 3057: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3058: 	    $languages{$lang}=1;
 3059:         }
 3060:     }
 3061:     return %languages;
 3062: }
 3063: 
 3064: sub languages {
 3065:     my ($possible_langs) = @_;
 3066:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3067:     if (!ref($possible_langs)) {
 3068: 	if( wantarray ) {
 3069: 	    return @preferred_langs;
 3070: 	} else {
 3071: 	    return $preferred_langs[0];
 3072: 	}
 3073:     }
 3074:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3075:     my @preferred_possibilities;
 3076:     foreach my $preferred_lang (@preferred_langs) {
 3077: 	if (exists($possibilities{$preferred_lang})) {
 3078: 	    push(@preferred_possibilities, $preferred_lang);
 3079: 	}
 3080:     }
 3081:     if( wantarray ) {
 3082: 	return @preferred_possibilities;
 3083:     }
 3084:     return $preferred_possibilities[0];
 3085: }
 3086: 
 3087: sub user_lang {
 3088:     my ($touname,$toudom,$fromcid) = @_;
 3089:     my @userlangs;
 3090:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3091:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3092:                     $env{'course.'.$fromcid.'.languages'}));
 3093:     } else {
 3094:         my %langhash = &getlangs($touname,$toudom);
 3095:         if ($langhash{'languages'} ne '') {
 3096:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3097:         } else {
 3098:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3099:             if ($domdefs{'lang_def'} ne '') {
 3100:                 @userlangs = ($domdefs{'lang_def'});
 3101:             }
 3102:         }
 3103:     }
 3104:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3105:     my $user_lh = Apache::localize->get_handle(@languages);
 3106:     return $user_lh;
 3107: }
 3108: 
 3109: 
 3110: ###############################################################
 3111: ##               Student Answer Attempts                     ##
 3112: ###############################################################
 3113: 
 3114: =pod
 3115: 
 3116: =head1 Alternate Problem Views
 3117: 
 3118: =over 4
 3119: 
 3120: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3121:     $getattempt, $regexp, $gradesub)
 3122: 
 3123: Return string with previous attempt on problem. Arguments:
 3124: 
 3125: =over 4
 3126: 
 3127: =item * $symb: Problem, including path
 3128: 
 3129: =item * $username: username of the desired student
 3130: 
 3131: =item * $domain: domain of the desired student
 3132: 
 3133: =item * $course: Course ID
 3134: 
 3135: =item * $getattempt: Leave blank for all attempts, otherwise put
 3136:     something
 3137: 
 3138: =item * $regexp: if string matches this regexp, the string will be
 3139:     sent to $gradesub
 3140: 
 3141: =item * $gradesub: routine that processes the string if it matches $regexp
 3142: 
 3143: =back
 3144: 
 3145: The output string is a table containing all desired attempts, if any.
 3146: 
 3147: =cut
 3148: 
 3149: sub get_previous_attempt {
 3150:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3151:   my $prevattempts='';
 3152:   no strict 'refs';
 3153:   if ($symb) {
 3154:     my (%returnhash)=
 3155:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3156:     if ($returnhash{'version'}) {
 3157:       my %lasthash=();
 3158:       my $version;
 3159:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3160:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3161: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3162:         }
 3163:       }
 3164:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3165:       $prevattempts.='<th>'.&mt('History').'</th>';
 3166:       foreach my $key (sort(keys(%lasthash))) {
 3167: 	my ($ign,@parts) = split(/\./,$key);
 3168: 	if ($#parts > 0) {
 3169: 	  my $data=$parts[-1];
 3170: 	  pop(@parts);
 3171: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3172: 	} else {
 3173: 	  if ($#parts == 0) {
 3174: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3175: 	  } else {
 3176: 	    $prevattempts.='<th>'.$ign.'</th>';
 3177: 	  }
 3178: 	}
 3179:       }
 3180:       $prevattempts.=&end_data_table_header_row();
 3181:       if ($getattempt eq '') {
 3182: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3183: 	  $prevattempts.=&start_data_table_row().
 3184: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3185: 	    foreach my $key (sort(keys(%lasthash))) {
 3186: 		my $value = &format_previous_attempt_value($key,
 3187: 							   $returnhash{$version.':'.$key});
 3188: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3189: 	    }
 3190: 	  $prevattempts.=&end_data_table_row();
 3191: 	 }
 3192:       }
 3193:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3194:       foreach my $key (sort(keys(%lasthash))) {
 3195: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3196: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3197: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3198:       }
 3199:       $prevattempts.= &end_data_table_row().&end_data_table();
 3200:     } else {
 3201:       $prevattempts=
 3202: 	  &start_data_table().&start_data_table_row().
 3203: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3204: 	  &end_data_table_row().&end_data_table();
 3205:     }
 3206:   } else {
 3207:     $prevattempts=
 3208: 	  &start_data_table().&start_data_table_row().
 3209: 	  '<td>'.&mt('No data.').'</td>'.
 3210: 	  &end_data_table_row().&end_data_table();
 3211:   }
 3212: }
 3213: 
 3214: sub format_previous_attempt_value {
 3215:     my ($key,$value) = @_;
 3216:     if ($key =~ /timestamp/) {
 3217: 	$value = &Apache::lonlocal::locallocaltime($value);
 3218:     } elsif (ref($value) eq 'ARRAY') {
 3219: 	$value = '('.join(', ', @{ $value }).')';
 3220:     } else {
 3221: 	$value = &unescape($value);
 3222:     }
 3223:     return $value;
 3224: }
 3225: 
 3226: 
 3227: sub relative_to_absolute {
 3228:     my ($url,$output)=@_;
 3229:     my $parser=HTML::TokeParser->new(\$output);
 3230:     my $token;
 3231:     my $thisdir=$url;
 3232:     my @rlinks=();
 3233:     while ($token=$parser->get_token) {
 3234: 	if ($token->[0] eq 'S') {
 3235: 	    if ($token->[1] eq 'a') {
 3236: 		if ($token->[2]->{'href'}) {
 3237: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3238: 		}
 3239: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3240: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3241: 	    } elsif ($token->[1] eq 'base') {
 3242: 		$thisdir=$token->[2]->{'href'};
 3243: 	    }
 3244: 	}
 3245:     }
 3246:     $thisdir=~s-/[^/]*$--;
 3247:     foreach my $link (@rlinks) {
 3248: 	unless (($link=~/^https?\:\/\//i) ||
 3249: 		($link=~/^\//) ||
 3250: 		($link=~/^javascript:/i) ||
 3251: 		($link=~/^mailto:/i) ||
 3252: 		($link=~/^\#/)) {
 3253: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3254: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3255: 	}
 3256:     }
 3257: # -------------------------------------------------- Deal with Applet codebases
 3258:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3259:     return $output;
 3260: }
 3261: 
 3262: =pod
 3263: 
 3264: =item * &get_student_view()
 3265: 
 3266: show a snapshot of what student was looking at
 3267: 
 3268: =cut
 3269: 
 3270: sub get_student_view {
 3271:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3272:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3273:   my (%form);
 3274:   my @elements=('symb','courseid','domain','username');
 3275:   foreach my $element (@elements) {
 3276:       $form{'grade_'.$element}=eval '$'.$element #'
 3277:   }
 3278:   if (defined($moreenv)) {
 3279:       %form=(%form,%{$moreenv});
 3280:   }
 3281:   if (defined($target)) { $form{'grade_target'} = $target; }
 3282:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3283:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3284:   $userview=~s/\<body[^\>]*\>//gi;
 3285:   $userview=~s/\<\/body\>//gi;
 3286:   $userview=~s/\<html\>//gi;
 3287:   $userview=~s/\<\/html\>//gi;
 3288:   $userview=~s/\<head\>//gi;
 3289:   $userview=~s/\<\/head\>//gi;
 3290:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3291:   $userview=&relative_to_absolute($feedurl,$userview);
 3292:   if (wantarray) {
 3293:      return ($userview,$response);
 3294:   } else {
 3295:      return $userview;
 3296:   }
 3297: }
 3298: 
 3299: sub get_student_view_with_retries {
 3300:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3301: 
 3302:     my $ok = 0;                 # True if we got a good response.
 3303:     my $content;
 3304:     my $response;
 3305: 
 3306:     # Try to get the student_view done. within the retries count:
 3307:     
 3308:     do {
 3309:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3310:          $ok      = $response->is_success;
 3311:          if (!$ok) {
 3312:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3313:          }
 3314:          $retries--;
 3315:     } while (!$ok && ($retries > 0));
 3316:     
 3317:     if (!$ok) {
 3318:        $content = '';          # On error return an empty content.
 3319:     }
 3320:     if (wantarray) {
 3321:        return ($content, $response);
 3322:     } else {
 3323:        return $content;
 3324:     }
 3325: }
 3326: 
 3327: =pod
 3328: 
 3329: =item * &get_student_answers() 
 3330: 
 3331: show a snapshot of how student was answering problem
 3332: 
 3333: =cut
 3334: 
 3335: sub get_student_answers {
 3336:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3337:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3338:   my (%moreenv);
 3339:   my @elements=('symb','courseid','domain','username');
 3340:   foreach my $element (@elements) {
 3341:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3342:   }
 3343:   $moreenv{'grade_target'}='answer';
 3344:   %moreenv=(%form,%moreenv);
 3345:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3346:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3347:   return $userview;
 3348: }
 3349: 
 3350: =pod
 3351: 
 3352: =item * &submlink()
 3353: 
 3354: Inputs: $text $uname $udom $symb $target
 3355: 
 3356: Returns: A link to grades.pm such as to see the SUBM view of a student
 3357: 
 3358: =cut
 3359: 
 3360: ###############################################
 3361: sub submlink {
 3362:     my ($text,$uname,$udom,$symb,$target)=@_;
 3363:     if (!($uname && $udom)) {
 3364: 	(my $cursymb, my $courseid,$udom,$uname)=
 3365: 	    &Apache::lonnet::whichuser($symb);
 3366: 	if (!$symb) { $symb=$cursymb; }
 3367:     }
 3368:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3369:     $symb=&escape($symb);
 3370:     if ($target) { $target="target=\"$target\""; }
 3371:     return '<a href="/adm/grades?&command=submission&'.
 3372: 	'symb='.$symb.'&student='.$uname.
 3373: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3374: }
 3375: ##############################################
 3376: 
 3377: =pod
 3378: 
 3379: =item * &pgrdlink()
 3380: 
 3381: Inputs: $text $uname $udom $symb $target
 3382: 
 3383: Returns: A link to grades.pm such as to see the PGRD view of a student
 3384: 
 3385: =cut
 3386: 
 3387: ###############################################
 3388: sub pgrdlink {
 3389:     my $link=&submlink(@_);
 3390:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3391:     return $link;
 3392: }
 3393: ##############################################
 3394: 
 3395: =pod
 3396: 
 3397: =item * &pprmlink()
 3398: 
 3399: Inputs: $text $uname $udom $symb $target
 3400: 
 3401: Returns: A link to parmset.pm such as to see the PPRM view of a
 3402: student and a specific resource
 3403: 
 3404: =cut
 3405: 
 3406: ###############################################
 3407: sub pprmlink {
 3408:     my ($text,$uname,$udom,$symb,$target)=@_;
 3409:     if (!($uname && $udom)) {
 3410: 	(my $cursymb, my $courseid,$udom,$uname)=
 3411: 	    &Apache::lonnet::whichuser($symb);
 3412: 	if (!$symb) { $symb=$cursymb; }
 3413:     }
 3414:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3415:     $symb=&escape($symb);
 3416:     if ($target) { $target="target=\"$target\""; }
 3417:     return '<a href="/adm/parmset?command=set&amp;'.
 3418: 	'symb='.$symb.'&amp;uname='.$uname.
 3419: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3420: }
 3421: ##############################################
 3422: 
 3423: =pod
 3424: 
 3425: =back
 3426: 
 3427: =cut
 3428: 
 3429: ###############################################
 3430: 
 3431: 
 3432: sub timehash {
 3433:     my ($thistime) = @_;
 3434:     my $timezone = &Apache::lonlocal::gettimezone();
 3435:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3436:                      ->set_time_zone($timezone);
 3437:     my $wday = $dt->day_of_week();
 3438:     if ($wday == 7) { $wday = 0; }
 3439:     return ( 'second' => $dt->second(),
 3440:              'minute' => $dt->minute(),
 3441:              'hour'   => $dt->hour(),
 3442:              'day'     => $dt->day_of_month(),
 3443:              'month'   => $dt->month(),
 3444:              'year'    => $dt->year(),
 3445:              'weekday' => $wday,
 3446:              'dayyear' => $dt->day_of_year(),
 3447:              'dlsav'   => $dt->is_dst() );
 3448: }
 3449: 
 3450: sub utc_string {
 3451:     my ($date)=@_;
 3452:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3453: }
 3454: 
 3455: sub maketime {
 3456:     my %th=@_;
 3457:     my ($epoch_time,$timezone,$dt);
 3458:     $timezone = &Apache::lonlocal::gettimezone();
 3459:     eval {
 3460:         $dt = DateTime->new( year   => $th{'year'},
 3461:                              month  => $th{'month'},
 3462:                              day    => $th{'day'},
 3463:                              hour   => $th{'hour'},
 3464:                              minute => $th{'minute'},
 3465:                              second => $th{'second'},
 3466:                              time_zone => $timezone,
 3467:                          );
 3468:     };
 3469:     if (!$@) {
 3470:         $epoch_time = $dt->epoch;
 3471:         if ($epoch_time) {
 3472:             return $epoch_time;
 3473:         }
 3474:     }
 3475:     return POSIX::mktime(
 3476:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3477:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3478: }
 3479: 
 3480: #########################################
 3481: 
 3482: sub findallcourses {
 3483:     my ($roles,$uname,$udom) = @_;
 3484:     my %roles;
 3485:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3486:     my %courses;
 3487:     my $now=time;
 3488:     if (!defined($uname)) {
 3489:         $uname = $env{'user.name'};
 3490:     }
 3491:     if (!defined($udom)) {
 3492:         $udom = $env{'user.domain'};
 3493:     }
 3494:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3495:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3496:         if (!%roles) {
 3497:             %roles = (
 3498:                        cc => 1,
 3499:                        in => 1,
 3500:                        ep => 1,
 3501:                        ta => 1,
 3502:                        cr => 1,
 3503:                        st => 1,
 3504:              );
 3505:         }
 3506:         foreach my $entry (keys(%roleshash)) {
 3507:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3508:             if ($trole =~ /^cr/) { 
 3509:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3510:             } else {
 3511:                 next if (!exists($roles{$trole}));
 3512:             }
 3513:             if ($tend) {
 3514:                 next if ($tend < $now);
 3515:             }
 3516:             if ($tstart) {
 3517:                 next if ($tstart > $now);
 3518:             }
 3519:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3520:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3521:             if ($secpart eq '') {
 3522:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3523:                 $sec = 'none';
 3524:                 $realsec = '';
 3525:             } else {
 3526:                 $cnum = $cnumpart;
 3527:                 ($sec,$role) = split(/_/,$secpart);
 3528:                 $realsec = $sec;
 3529:             }
 3530:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3531:         }
 3532:     } else {
 3533:         foreach my $key (keys(%env)) {
 3534: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3535:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3536: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3537: 	        next if ($role eq 'ca' || $role eq 'aa');
 3538: 	        next if (%roles && !exists($roles{$role}));
 3539: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3540:                 my $active=1;
 3541:                 if ($starttime) {
 3542: 		    if ($now<$starttime) { $active=0; }
 3543:                 }
 3544:                 if ($endtime) {
 3545:                     if ($now>$endtime) { $active=0; }
 3546:                 }
 3547:                 if ($active) {
 3548:                     if ($sec eq '') {
 3549:                         $sec = 'none';
 3550:                     }
 3551:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3552:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3553:                 }
 3554:             }
 3555:         }
 3556:     }
 3557:     return %courses;
 3558: }
 3559: 
 3560: ###############################################
 3561: 
 3562: sub blockcheck {
 3563:     my ($setters,$activity,$uname,$udom) = @_;
 3564: 
 3565:     if (!defined($udom)) {
 3566:         $udom = $env{'user.domain'};
 3567:     }
 3568:     if (!defined($uname)) {
 3569:         $uname = $env{'user.name'};
 3570:     }
 3571: 
 3572:     # If uname and udom are for a course, check for blocks in the course.
 3573: 
 3574:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3575:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3576:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3577:         return ($startblock,$endblock);
 3578:     }
 3579: 
 3580:     my $startblock = 0;
 3581:     my $endblock = 0;
 3582:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3583: 
 3584:     # If uname is for a user, and activity is course-specific, i.e.,
 3585:     # boards, chat or groups, check for blocking in current course only.
 3586: 
 3587:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3588:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3589:         foreach my $key (keys(%live_courses)) {
 3590:             if ($key ne $env{'request.course.id'}) {
 3591:                 delete($live_courses{$key});
 3592:             }
 3593:         }
 3594:     }
 3595: 
 3596:     my $otheruser = 0;
 3597:     my %own_courses;
 3598:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3599:         # Resource belongs to user other than current user.
 3600:         $otheruser = 1;
 3601:         # Gather courses for current user
 3602:         %own_courses = 
 3603:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3604:     }
 3605: 
 3606:     # Gather active course roles - course coordinator, instructor, 
 3607:     # exam proctor, ta, student, or custom role.
 3608: 
 3609:     foreach my $course (keys(%live_courses)) {
 3610:         my ($cdom,$cnum);
 3611:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3612:             $cdom = $env{'course.'.$course.'.domain'};
 3613:             $cnum = $env{'course.'.$course.'.num'};
 3614:         } else {
 3615:             ($cdom,$cnum) = split(/_/,$course); 
 3616:         }
 3617:         my $no_ownblock = 0;
 3618:         my $no_userblock = 0;
 3619:         if ($otheruser && $activity ne 'com') {
 3620:             # Check if current user has 'evb' priv for this
 3621:             if (defined($own_courses{$course})) {
 3622:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3623:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3624:                     if ($sec ne 'none') {
 3625:                         $checkrole .= '/'.$sec;
 3626:                     }
 3627:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3628:                         $no_ownblock = 1;
 3629:                         last;
 3630:                     }
 3631:                 }
 3632:             }
 3633:             # if they have 'evb' priv and are currently not playing student
 3634:             next if (($no_ownblock) &&
 3635:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3636:         }
 3637:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3638:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3639:             if ($sec ne 'none') {
 3640:                 $checkrole .= '/'.$sec;
 3641:             }
 3642:             if ($otheruser) {
 3643:                 # Resource belongs to user other than current user.
 3644:                 # Assemble privs for that user, and check for 'evb' priv.
 3645:                 my ($trole,$tdom,$tnum,$tsec);
 3646:                 my $entry = $live_courses{$course}{$sec};
 3647:                 if ($entry =~ /^cr/) {
 3648:                     ($trole,$tdom,$tnum,$tsec) = 
 3649:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3650:                 } else {
 3651:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3652:                 }
 3653:                 my ($spec,$area,$trest,%allroles,%userroles);
 3654:                 $area = '/'.$tdom.'/'.$tnum;
 3655:                 $trest = $tnum;
 3656:                 if ($tsec ne '') {
 3657:                     $area .= '/'.$tsec;
 3658:                     $trest .= '/'.$tsec;
 3659:                 }
 3660:                 $spec = $trole.'.'.$area;
 3661:                 if ($trole =~ /^cr/) {
 3662:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3663:                                                       $tdom,$spec,$trest,$area);
 3664:                 } else {
 3665:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3666:                                                        $tdom,$spec,$trest,$area);
 3667:                 }
 3668:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3669:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3670:                     if ($1) {
 3671:                         $no_userblock = 1;
 3672:                         last;
 3673:                     }
 3674:                 }
 3675:             } else {
 3676:                 # Resource belongs to current user
 3677:                 # Check for 'evb' priv via lonnet::allowed().
 3678:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3679:                     $no_ownblock = 1;
 3680:                     last;
 3681:                 }
 3682:             }
 3683:         }
 3684:         # if they have the evb priv and are currently not playing student
 3685:         next if (($no_ownblock) &&
 3686:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3687:         next if ($no_userblock);
 3688: 
 3689:         # Retrieve blocking times and identity of blocker for course
 3690:         # of specified user, unless user has 'evb' privilege.
 3691:         
 3692:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3693:         if (($start != 0) && 
 3694:             (($startblock == 0) || ($startblock > $start))) {
 3695:             $startblock = $start;
 3696:         }
 3697:         if (($end != 0)  &&
 3698:             (($endblock == 0) || ($endblock < $end))) {
 3699:             $endblock = $end;
 3700:         }
 3701:     }
 3702:     return ($startblock,$endblock);
 3703: }
 3704: 
 3705: sub get_blocks {
 3706:     my ($setters,$activity,$cdom,$cnum) = @_;
 3707:     my $startblock = 0;
 3708:     my $endblock = 0;
 3709:     my $course = $cdom.'_'.$cnum;
 3710:     $setters->{$course} = {};
 3711:     $setters->{$course}{'staff'} = [];
 3712:     $setters->{$course}{'times'} = [];
 3713:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3714:     foreach my $record (keys(%records)) {
 3715:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3716:         if ($start <= time && $end >= time) {
 3717:             my ($staff_name,$staff_dom,$title,$blocks) =
 3718:                 &parse_block_record($records{$record});
 3719:             if ($blocks->{$activity} eq 'on') {
 3720:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3721:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3722:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3723:                     $startblock = $start;
 3724:                 }
 3725:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3726:                     $endblock = $end;
 3727:                 }
 3728:             }
 3729:         }
 3730:     }
 3731:     return ($startblock,$endblock);
 3732: }
 3733: 
 3734: sub parse_block_record {
 3735:     my ($record) = @_;
 3736:     my ($setuname,$setudom,$title,$blocks);
 3737:     if (ref($record) eq 'HASH') {
 3738:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3739:         $title = &unescape($record->{'event'});
 3740:         $blocks = $record->{'blocks'};
 3741:     } else {
 3742:         my @data = split(/:/,$record,3);
 3743:         if (scalar(@data) eq 2) {
 3744:             $title = $data[1];
 3745:             ($setuname,$setudom) = split(/@/,$data[0]);
 3746:         } else {
 3747:             ($setuname,$setudom,$title) = @data;
 3748:         }
 3749:         $blocks = { 'com' => 'on' };
 3750:     }
 3751:     return ($setuname,$setudom,$title,$blocks);
 3752: }
 3753: 
 3754: sub build_block_table {
 3755:     my ($startblock,$endblock,$setters) = @_;
 3756:     my %lt = &Apache::lonlocal::texthash(
 3757:         'cacb' => 'Currently active communication blocks',
 3758:         'cour' => 'Course',
 3759:         'dura' => 'Duration',
 3760:         'blse' => 'Block set by'
 3761:     );
 3762:     my $output;
 3763:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3764:     $output .= &start_data_table();
 3765:     $output .= '
 3766: <tr>
 3767:  <th>'.$lt{'cour'}.'</th>
 3768:  <th>'.$lt{'dura'}.'</th>
 3769:  <th>'.$lt{'blse'}.'</th>
 3770: </tr>
 3771: ';
 3772:     foreach my $course (keys(%{$setters})) {
 3773:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3774:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3775:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3776:             my $fullname = &plainname($uname,$udom);
 3777:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3778:                 && $env{'user.name'} ne 'public' 
 3779:                 && $env{'user.domain'} ne 'public') {
 3780:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3781:             }
 3782:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3783:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3784:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3785:             $output .= &Apache::loncommon::start_data_table_row().
 3786:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3787:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3788:                        '<td>'.$fullname.'</td>'.
 3789:                         &Apache::loncommon::end_data_table_row();
 3790:         }
 3791:     }
 3792:     $output .= &end_data_table();
 3793: }
 3794: 
 3795: sub blocking_status {
 3796:     my ($activity,$uname,$udom) = @_;
 3797:     my %setters;
 3798:     my ($blocked,$output,$ownitem,$is_course);
 3799:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3800:     if ($startblock && $endblock) {
 3801:         $blocked = 1;
 3802:         if (wantarray) {
 3803:             my $category;
 3804:             if ($activity eq 'boards') {
 3805:                 $category = 'Discussion posts in this course';
 3806:             } elsif ($activity eq 'blogs') {
 3807:                 $category = 'Blogs';
 3808:             } elsif ($activity eq 'port') {
 3809:                 if (defined($uname) && defined($udom)) {
 3810:                     if ($uname eq $env{'user.name'} &&
 3811:                         $udom eq $env{'user.domain'}) {
 3812:                         $ownitem = 1;
 3813:                     }
 3814:                 }
 3815:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3816:                 if ($ownitem) { 
 3817:                     $category = 'Your portfolio files';  
 3818:                 } elsif ($is_course) {
 3819:                     my $coursedesc;
 3820:                     foreach my $course (keys(%setters)) {
 3821:                         my %courseinfo =
 3822:                              &Apache::lonnet::coursedescription($course);
 3823:                         $coursedesc = $courseinfo{'description'};
 3824:                     }
 3825:                     $category = "Group portfolio in the course '$coursedesc'";
 3826:                 } else {
 3827:                     $category = 'Portfolio files belonging to ';
 3828:                     if ($env{'user.name'} eq 'public' && 
 3829:                         $env{'user.domain'} eq 'public') {
 3830:                         $category .= &plainname($uname,$udom);
 3831:                     } else {
 3832:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3833:                     }
 3834:                 }
 3835:             } elsif ($activity eq 'groups') {
 3836:                 $category = 'Groups in this course';
 3837:             }
 3838:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3839:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3840:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3841:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3842:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3843:             }
 3844:         }
 3845:     }
 3846:     if (wantarray) {
 3847:         return ($blocked,$output);
 3848:     } else {
 3849:         return $blocked;
 3850:     }
 3851: }
 3852: 
 3853: ###############################################
 3854: 
 3855: sub check_ip_acc {
 3856:     my ($acc)=@_;
 3857:     &Apache::lonxml::debug("acc is $acc");
 3858:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3859:         return 1;
 3860:     }
 3861:     my $allowed=0;
 3862:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3863: 
 3864:     my $name;
 3865:     foreach my $pattern (split(',',$acc)) {
 3866:         $pattern =~ s/^\s*//;
 3867:         $pattern =~ s/\s*$//;
 3868:         if ($pattern =~ /\*$/) {
 3869:             #35.8.*
 3870:             $pattern=~s/\*//;
 3871:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3872:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3873:             #35.8.3.[34-56]
 3874:             my $low=$2;
 3875:             my $high=$3;
 3876:             $pattern=$1;
 3877:             if ($ip =~ /^\Q$pattern\E/) {
 3878:                 my $last=(split(/\./,$ip))[3];
 3879:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3880:             }
 3881:         } elsif ($pattern =~ /^\*/) {
 3882:             #*.msu.edu
 3883:             $pattern=~s/\*//;
 3884:             if (!defined($name)) {
 3885:                 use Socket;
 3886:                 my $netaddr=inet_aton($ip);
 3887:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3888:             }
 3889:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3890:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3891:             #127.0.0.1
 3892:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3893:         } else {
 3894:             #some.name.com
 3895:             if (!defined($name)) {
 3896:                 use Socket;
 3897:                 my $netaddr=inet_aton($ip);
 3898:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3899:             }
 3900:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3901:         }
 3902:         if ($allowed) { last; }
 3903:     }
 3904:     return $allowed;
 3905: }
 3906: 
 3907: ###############################################
 3908: 
 3909: =pod
 3910: 
 3911: =head1 Domain Template Functions
 3912: 
 3913: =over 4
 3914: 
 3915: =item * &determinedomain()
 3916: 
 3917: Inputs: $domain (usually will be undef)
 3918: 
 3919: Returns: Determines which domain should be used for designs
 3920: 
 3921: =cut
 3922: 
 3923: ###############################################
 3924: sub determinedomain {
 3925:     my $domain=shift;
 3926:     if (! $domain) {
 3927:         # Determine domain if we have not been given one
 3928:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3929:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3930:         if ($env{'request.role.domain'}) { 
 3931:             $domain=$env{'request.role.domain'}; 
 3932:         }
 3933:     }
 3934:     return $domain;
 3935: }
 3936: ###############################################
 3937: 
 3938: sub devalidate_domconfig_cache {
 3939:     my ($udom)=@_;
 3940:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3941: }
 3942: 
 3943: # ---------------------- Get domain configuration for a domain
 3944: sub get_domainconf {
 3945:     my ($udom) = @_;
 3946:     my $cachetime=1800;
 3947:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3948:     if (defined($cached)) { return %{$result}; }
 3949: 
 3950:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3951: 					     ['login','rolecolors'],$udom);
 3952:     my (%designhash,%legacy);
 3953:     if (keys(%domconfig) > 0) {
 3954:         if (ref($domconfig{'login'}) eq 'HASH') {
 3955:             if (keys(%{$domconfig{'login'}})) {
 3956:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3957:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3958:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3959:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 3960:                                 $domconfig{'login'}{$key}{$img};
 3961:                         }
 3962:                     } else {
 3963:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3964:                     }
 3965:                 }
 3966:             } else {
 3967:                 $legacy{'login'} = 1;
 3968:             }
 3969:         } else {
 3970:             $legacy{'login'} = 1;
 3971:         }
 3972:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3973:             if (keys(%{$domconfig{'rolecolors'}})) {
 3974:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3975:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3976:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3977:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3978:                         }
 3979:                     }
 3980:                 }
 3981:             } else {
 3982:                 $legacy{'rolecolors'} = 1;
 3983:             }
 3984:         } else {
 3985:             $legacy{'rolecolors'} = 1;
 3986:         }
 3987:         if (keys(%legacy) > 0) {
 3988:             my %legacyhash = &get_legacy_domconf($udom);
 3989:             foreach my $item (keys(%legacyhash)) {
 3990:                 if ($item =~ /^\Q$udom\E\.login/) {
 3991:                     if ($legacy{'login'}) { 
 3992:                         $designhash{$item} = $legacyhash{$item};
 3993:                     }
 3994:                 } else {
 3995:                     if ($legacy{'rolecolors'}) {
 3996:                         $designhash{$item} = $legacyhash{$item};
 3997:                     }
 3998:                 }
 3999:             }
 4000:         }
 4001:     } else {
 4002:         %designhash = &get_legacy_domconf($udom); 
 4003:     }
 4004:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4005: 				  $cachetime);
 4006:     return %designhash;
 4007: }
 4008: 
 4009: sub get_legacy_domconf {
 4010:     my ($udom) = @_;
 4011:     my %legacyhash;
 4012:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4013:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4014:     if (-e $designfile) {
 4015:         if ( open (my $fh,"<$designfile") ) {
 4016:             while (my $line = <$fh>) {
 4017:                 next if ($line =~ /^\#/);
 4018:                 chomp($line);
 4019:                 my ($key,$val)=(split(/\=/,$line));
 4020:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4021:             }
 4022:             close($fh);
 4023:         }
 4024:     }
 4025:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4026:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4027:     }
 4028:     return %legacyhash;
 4029: }
 4030: 
 4031: =pod
 4032: 
 4033: =item * &domainlogo()
 4034: 
 4035: Inputs: $domain (usually will be undef)
 4036: 
 4037: Returns: A link to a domain logo, if the domain logo exists.
 4038: If the domain logo does not exist, a description of the domain.
 4039: 
 4040: =cut
 4041: 
 4042: ###############################################
 4043: sub domainlogo {
 4044:     my $domain = &determinedomain(shift);
 4045:     my %designhash = &get_domainconf($domain);    
 4046:     # See if there is a logo
 4047:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4048:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4049:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4050: 	    if ($imgsrc =~ m{^/res/}) {
 4051: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4052: 		&Apache::lonnet::repcopy($local_name);
 4053: 	    }
 4054: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4055:         } 
 4056:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4057:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4058:         return &Apache::lonnet::domain($domain,'description');
 4059:     } else {
 4060:         return '';
 4061:     }
 4062: }
 4063: ##############################################
 4064: 
 4065: =pod
 4066: 
 4067: =item * &designparm()
 4068: 
 4069: Inputs: $which parameter; $domain (usually will be undef)
 4070: 
 4071: Returns: value of designparamter $which
 4072: 
 4073: =cut
 4074: 
 4075: 
 4076: ##############################################
 4077: sub designparm {
 4078:     my ($which,$domain)=@_;
 4079:     if ($env{'browser.blackwhite'} eq 'on') {
 4080: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4081: 	    return '#000000';
 4082: 	}
 4083: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4084: 	    return '#FFFFFF';
 4085: 	}
 4086: 	if ($which=~/\.tabbg$/) {
 4087: 	    return '#CCCCCC';
 4088: 	}
 4089:     }
 4090:     if (exists($env{'environment.color.'.$which})) {
 4091: 	return $env{'environment.color.'.$which};
 4092:     }
 4093:     $domain=&determinedomain($domain);
 4094:     my %domdesign = &get_domainconf($domain);
 4095:     my $output;
 4096:     if ($domdesign{$domain.'.'.$which} ne '') {
 4097: 	$output = $domdesign{$domain.'.'.$which};
 4098:     } else {
 4099:         $output = $defaultdesign{$which};
 4100:     }
 4101:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4102:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4103:         if ($output =~ m{^/(adm|res)/}) {
 4104: 	    if ($output =~ m{^/res/}) {
 4105: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4106: 		&Apache::lonnet::repcopy($local_name);
 4107: 	    }
 4108:             $output = &lonhttpdurl($output);
 4109:         }
 4110:     }
 4111:     return $output;
 4112: }
 4113: 
 4114: ###############################################
 4115: ###############################################
 4116: 
 4117: =pod
 4118: 
 4119: =back
 4120: 
 4121: =head1 HTML Helpers
 4122: 
 4123: =over 4
 4124: 
 4125: =item * &bodytag()
 4126: 
 4127: Returns a uniform header for LON-CAPA web pages.
 4128: 
 4129: Inputs: 
 4130: 
 4131: =over 4
 4132: 
 4133: =item * $title, A title to be displayed on the page.
 4134: 
 4135: =item * $function, the current role (can be undef).
 4136: 
 4137: =item * $addentries, extra parameters for the <body> tag.
 4138: 
 4139: =item * $bodyonly, if defined, only return the <body> tag.
 4140: 
 4141: =item * $domain, if defined, force a given domain.
 4142: 
 4143: =item * $forcereg, if page should register as content page (relevant for 
 4144:             text interface only)
 4145: 
 4146: =item * $customtitle, 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: 
 4150: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4151:                    navigational links
 4152: 
 4153: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4154: 
 4155: =item * $notitle, if true keep the nav controls, but remove the title bar
 4156: 
 4157: =item * $no_inline_link, if true and in remote mode, don't show the 
 4158:          'Switch To Inline Menu' link
 4159: 
 4160: =item * $args, optional argument valid values are
 4161:             no_auto_mt_title -> prevents &mt()ing the title arg
 4162:             inherit_jsmath -> when creating popup window in a page,
 4163:                               should it have jsmath forced on by the
 4164:                               current page
 4165: 
 4166: =back
 4167: 
 4168: Returns: A uniform header for LON-CAPA web pages.  
 4169: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4170: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4171: other decorations will be returned.
 4172: 
 4173: =cut
 4174: 
 4175: sub bodytag {
 4176:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4177: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4178: 
 4179:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4180: 
 4181:     $function = &get_users_function() if (!$function);
 4182:     my $img =    &designparm($function.'.img',$domain);
 4183:     my $font =   &designparm($function.'.font',$domain);
 4184:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4185: 
 4186:     my %design = ( 'style'   => 'margin-top: 0px',
 4187: 		   'bgcolor' => $pgbg,
 4188: 		   'text'    => $font,
 4189:                    'alink'   => &designparm($function.'.alink',$domain),
 4190: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4191: 		   'link'    => &designparm($function.'.link',$domain),);
 4192:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4193: 
 4194:  # role and realm
 4195:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4196:     if ($role  eq 'ca') {
 4197:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4198:         $realm = &plainname($rname,$rdom);
 4199:     } 
 4200: # realm
 4201:     if ($env{'request.course.id'}) {
 4202:         if ($env{'request.role'} !~ /^cr/) {
 4203:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4204:         }
 4205: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4206:     } else {
 4207:         $role = &Apache::lonnet::plaintext($role);
 4208:     }
 4209: 
 4210:     if (!$realm) { $realm='&nbsp;'; }
 4211: # Set messages
 4212:     my $messages=&domainlogo($domain);
 4213: 
 4214:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4215: 
 4216: # construct main body tag
 4217:     my $bodytag = "<body $extra_body_attr>".
 4218: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4219: 
 4220:     if ($bodyonly) {
 4221:         return $bodytag;
 4222:     } elsif ($env{'browser.interface'} eq 'textual') {
 4223: # Accessibility
 4224:           
 4225: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4226: 	if (!$notitle) {
 4227: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4228: 	}
 4229: 	return $bodytag;
 4230:     }
 4231: 
 4232:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4233:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4234: 	undef($role);
 4235:     } else {
 4236: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4237:     }
 4238:     
 4239:     my $roleinfo=(<<ENDROLE);
 4240: <td class="LC_title_bar_who">
 4241: <div class="LC_title_bar_name">
 4242:     $name
 4243:     &nbsp;
 4244: </div>
 4245: <div class="LC_title_bar_role">
 4246: $role&nbsp;
 4247: </div>
 4248: <div class="LC_title_bar_realm">
 4249: $realm&nbsp;
 4250: </div>
 4251: </td>
 4252: ENDROLE
 4253: 
 4254:     my $titleinfo = '<h1>'.$title.'</h1>';
 4255:     if ($customtitle) {
 4256:         $titleinfo = $customtitle;
 4257:     }
 4258:     #
 4259:     # Extra info if you are the DC
 4260:     my $dc_info = '';
 4261:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4262:                         $env{'course.'.$env{'request.course.id'}.
 4263:                                  '.domain'}.'/'})) {
 4264:         my $cid = $env{'request.course.id'};
 4265:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4266:         $dc_info =~ s/\s+$//;
 4267:         $dc_info = '('.$dc_info.')';
 4268:     }
 4269: 
 4270:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4271:         # No Remote
 4272: 	if ($env{'request.state'} eq 'construct') {
 4273: 	    $forcereg=1;
 4274: 	}
 4275: 
 4276: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4277: 	    # this is for resources; directories have customtitle, and crumbs
 4278:             # and select recent are created in lonpubdir.pm  
 4279: 	    my ($uname,$thisdisfn)=
 4280: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4281: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4282: 	    $formaction=~s/\/+/\//g;
 4283: 
 4284: 	    my $parentpath = '';
 4285: 	    my $lastitem = '';
 4286: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4287: 		$parentpath = $1;
 4288: 		$lastitem = $2;
 4289: 	    } else {
 4290: 		$lastitem = $thisdisfn;
 4291: 	    }
 4292: 	    $titleinfo = 
 4293: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4294: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4295: 		.'<form name="dirs" method="post" action="'.$formaction
 4296: 		.'" target="_top"><tt><b>'
 4297: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4298: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4299: 		.'</form>'
 4300: 		.&Apache::lonmenu::constspaceform();
 4301:         }
 4302: 
 4303:         my $titletable;
 4304: 	if (!$notitle) {
 4305: 	    $titletable =
 4306: 		'<table id="LC_title_bar">'.
 4307:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4308: 			 '</tr></table>';
 4309: 	}
 4310: 	if ($notopbar) {
 4311: 	    $bodytag .= $titletable;
 4312: 	} else {
 4313: 	    if ($env{'request.state'} eq 'construct') {
 4314:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4315: 							  $titletable);
 4316:             } else {
 4317:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4318: 		    $titletable;
 4319:             }
 4320:         }
 4321:         return $bodytag;
 4322:     }
 4323: 
 4324: #
 4325: # Top frame rendering, Remote is up
 4326: #
 4327: 
 4328:     my $imgsrc = $img;
 4329:     if ($img =~ /^\/adm/) {
 4330:         $imgsrc = &lonhttpdurl($img);
 4331:     }
 4332:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4333: 
 4334:     # Explicit link to get inline menu
 4335:     my $menu= ($no_inline_link?''
 4336: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4337:     #
 4338:     if ($notitle) {
 4339: 	return $bodytag;
 4340:     }
 4341:     return(<<ENDBODY);
 4342: $bodytag
 4343: <table id="LC_title_bar" class="LC_with_remote">
 4344: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4345:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4346: </tr>
 4347: <tr><td>$titleinfo $dc_info $menu</td>
 4348: $roleinfo
 4349: </tr>
 4350: </table>
 4351: ENDBODY
 4352: }
 4353: 
 4354: sub make_attr_string {
 4355:     my ($register,$attr_ref) = @_;
 4356: 
 4357:     if ($attr_ref && !ref($attr_ref)) {
 4358: 	die("addentries Must be a hash ref ".
 4359: 	    join(':',caller(1))." ".
 4360: 	    join(':',caller(0))." ");
 4361:     }
 4362: 
 4363:     if ($register) {
 4364: 	my ($on_load,$on_unload);
 4365: 	foreach my $key (keys(%{$attr_ref})) {
 4366: 	    if      (lc($key) eq 'onload') {
 4367: 		$on_load.=$attr_ref->{$key}.';';
 4368: 		delete($attr_ref->{$key});
 4369: 
 4370: 	    } elsif (lc($key) eq 'onunload') {
 4371: 		$on_unload.=$attr_ref->{$key}.';';
 4372: 		delete($attr_ref->{$key});
 4373: 	    }
 4374: 	}
 4375: 	$attr_ref->{'onload'}  =
 4376: 	    &Apache::lonmenu::loadevents().  $on_load;
 4377: 	$attr_ref->{'onunload'}=
 4378: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4379:     }
 4380: 
 4381: # Accessibility font enhance
 4382:     if ($env{'browser.fontenhance'} eq 'on') {
 4383: 	my $style;
 4384: 	foreach my $key (keys(%{$attr_ref})) {
 4385: 	    if (lc($key) eq 'style') {
 4386: 		$style.=$attr_ref->{$key}.';';
 4387: 		delete($attr_ref->{$key});
 4388: 	    }
 4389: 	}
 4390: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4391:     }
 4392: 
 4393:     if ($env{'browser.blackwhite'} eq 'on') {
 4394: 	delete($attr_ref->{'font'});
 4395: 	delete($attr_ref->{'link'});
 4396: 	delete($attr_ref->{'alink'});
 4397: 	delete($attr_ref->{'vlink'});
 4398: 	delete($attr_ref->{'bgcolor'});
 4399: 	delete($attr_ref->{'background'});
 4400:     }
 4401: 
 4402:     my $attr_string;
 4403:     foreach my $attr (keys(%$attr_ref)) {
 4404: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4405:     }
 4406:     return $attr_string;
 4407: }
 4408: 
 4409: 
 4410: ###############################################
 4411: ###############################################
 4412: 
 4413: =pod
 4414: 
 4415: =item * &endbodytag()
 4416: 
 4417: Returns a uniform footer for LON-CAPA web pages.
 4418: 
 4419: Inputs: 1 - optional reference to an args hash
 4420: If in the hash, key for noredirectlink has a value which evaluates to true,
 4421: a 'Continue' link is not displayed if the page contains an
 4422: internal redirect in the <head></head> section,
 4423: i.e., $env{'internal.head.redirect'} exists   
 4424: 
 4425: =cut
 4426: 
 4427: sub endbodytag {
 4428:     my ($args) = @_;
 4429:     my $endbodytag='</body>';
 4430:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4431:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4432:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4433: 	    $endbodytag=
 4434: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4435: 	        &mt('Continue').'</a>'.
 4436: 	        $endbodytag;
 4437:         }
 4438:     }
 4439:     return $endbodytag;
 4440: }
 4441: 
 4442: =pod
 4443: 
 4444: =item * &standard_css()
 4445: 
 4446: Returns a style sheet
 4447: 
 4448: Inputs: (all optional)
 4449:             domain         -> force to color decorate a page for a specific
 4450:                                domain
 4451:             function       -> force usage of a specific rolish color scheme
 4452:             bgcolor        -> override the default page bgcolor
 4453: 
 4454: =cut
 4455: 
 4456: sub standard_css {
 4457:     my ($function,$domain,$bgcolor) = @_;
 4458:     $function  = &get_users_function() if (!$function);
 4459:     my $img    = &designparm($function.'.img',   $domain);
 4460:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4461:     my $font   = &designparm($function.'.font',  $domain);
 4462:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4463:     my $pgbg_or_bgcolor =
 4464: 	         $bgcolor ||
 4465: 	         &designparm($function.'.pgbg',  $domain);
 4466:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4467:     my $alink  = &designparm($function.'.alink', $domain);
 4468:     my $vlink  = &designparm($function.'.vlink', $domain);
 4469:     my $link   = &designparm($function.'.link',  $domain);
 4470: 
 4471:     my $loginbg = &designparm('login.sidebg',$domain);
 4472:     my $bgcol = &designparm('login.bgcol',$domain);
 4473:     my $textcol = &designparm('login.textcol',$domain);
 4474: 
 4475:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4476:     my $mono                 = 'monospace';
 4477:     my $data_table_head      = $tabbg;
 4478:     my $data_table_light     = '#EEEEEE';
 4479:     my $data_table_dark      = '#DDDDDD';
 4480:     my $data_table_darker    = '#CCCCCC';
 4481:     my $data_table_highlight = '#FFFF00';
 4482:     my $mail_new             = '#FFBB77';
 4483:     my $mail_new_hover       = '#DD9955';
 4484:     my $mail_read            = '#BBBB77';
 4485:     my $mail_read_hover      = '#999944';
 4486:     my $mail_replied         = '#AAAA88';
 4487:     my $mail_replied_hover   = '#888855';
 4488:     my $mail_other           = '#99BBBB';
 4489:     my $mail_other_hover     = '#669999';
 4490:     my $table_header         = '#DDDDDD';
 4491:     my $feedback_link_bg     = '#BBBBBB';
 4492:     my $lg_border_color	     = '#C8C8C8';
 4493: 
 4494:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4495: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4496: 	                                                 : '0px 3px 0px 4px';
 4497: 
 4498: 
 4499:     return <<END;
 4500: body{
 4501:      font-family: $sans;
 4502:      line-height:130%;
 4503:      font-size:0.83em;
 4504:      color:$font;
 4505:   }
 4506: a:link, a:visited { font-size:100%; }
 4507: 
 4508: a:focus { color: red; background: yellow } 
 4509: table.thinborder,
 4510: table.thinborder tr th {
 4511:   border-style: solid;
 4512:   border-width: 1px;
 4513:   border-color: $lg_border_color;
 4514:   background: $tabbg;
 4515: }
 4516: table.thinborder tr td {
 4517:   border-style: solid;
 4518:   border-width: 1px;
 4519:   border-color: $lg_border_color;
 4520: }
 4521: 
 4522: form, .inline { display: inline; }
 4523: 
 4524: .LC_right {text-align:right;}
 4525: .LC_middle {vertical-align:middle;}
 4526: 
 4527: /* just for tests */
 4528: .LC_400Box {width:400px; }
 4529: /* end */
 4530: 
 4531: .LC_filename {font-family: $mono; white-space:pre;}
 4532: .LC_error {
 4533:   color: red;
 4534:   font-size: larger;
 4535: }
 4536: .LC_warning,
 4537: .LC_diff_removed {
 4538:   color: red;
 4539: }
 4540: 
 4541: .LC_info,
 4542: .LC_success,
 4543: .LC_diff_added {
 4544:   color: green;
 4545: }
 4546: .LC_unknown {
 4547:   color: yellow;
 4548: }
 4549: 
 4550: .LC_icon {
 4551:   border: none;
 4552: }
 4553: 
 4554: .LC_indexer_icon {
 4555:   border: 0px;
 4556:   height: 22px;
 4557: }
 4558: .LC_docs_spacer {
 4559:   width: 25px;
 4560:   height: 1px;
 4561:   border: none;
 4562: }
 4563: 
 4564: .LC_internal_info {
 4565:   color: #999999;
 4566: }
 4567: 
 4568: table.LC_pastsubmission {
 4569:   border: 1px solid black;
 4570:   margin: 2px;
 4571: }
 4572: 
 4573: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4574:   width: 100%;
 4575:   background: $pgbg;
 4576:   border: 2px;
 4577:   border-collapse: separate;
 4578:   padding: 0px;
 4579: }
 4580: 
 4581: table#LC_title_bar, table.LC_breadcrumbs, 
 4582: table#LC_title_bar.LC_with_remote {
 4583:   width: 100%;
 4584:   border-color: $pgbg;
 4585:   border-style: solid;
 4586:   border-width: $border;
 4587: 
 4588:   background: $pgbg;
 4589:   font-family: $sans;
 4590:   border-collapse: collapse;
 4591:   padding: 0px;
 4592: }
 4593: table.LC_docs_path {
 4594:   width: 100%;
 4595:   border: 0;
 4596:   background: $pgbg;
 4597:   font-family: $sans;
 4598:   border-collapse: collapse;
 4599:   padding: 0px;
 4600: }
 4601: 
 4602: table#LC_title_bar td {
 4603:   background: $tabbg;
 4604: }
 4605: table#LC_title_bar .LC_title_bar_who {
 4606:   background: $tabbg;
 4607:   color: $font;
 4608:   font: small $sans;
 4609:   text-align: right;
 4610:   margin: 0px;
 4611: }
 4612: table#LC_title_bar .LC_title_bar_name {
 4613:   margin: 0px;
 4614: }
 4615: table#LC_title_bar .LC_title_bar_role {
 4616:   margin: 0px;
 4617: }
 4618: table#LC_title_bar .LC_title_bar_realm {
 4619:   margin: 0px;
 4620: }
 4621: span.LC_metadata {
 4622:     font-family: $sans;
 4623: }
 4624: table#LC_title_bar td.LC_title_bar_domain_logo {
 4625:   background: $sidebg;
 4626:   text-align: right;
 4627:   padding: 0px;
 4628: }
 4629: table#LC_title_bar td.LC_title_bar_role_logo {
 4630:   background: $sidebg;
 4631:   padding: 0px;
 4632: }
 4633: 
 4634: table#LC_menubuttons img{
 4635:   border: 0px;
 4636: }
 4637: table#LC_top_nav td {
 4638:   background: $tabbg;
 4639:   border: 0px;
 4640:   font-size: small;
 4641:   vertical-align:top;
 4642:   padding:2px 5px 2px 5px;
 4643: }
 4644: table#LC_top_nav td a, div#LC_top_nav a {
 4645:   color: $font;
 4646:   font-family: $sans;
 4647: }
 4648: table#LC_top_nav td.LC_top_nav_logo {
 4649:   background: $tabbg;
 4650:   text-align: left;
 4651:   white-space: nowrap;
 4652:   width: 31px;
 4653: }
 4654: table#LC_top_nav td.LC_top_nav_logo img {
 4655:   border: 0px;
 4656:   vertical-align: bottom;
 4657: }
 4658: table#LC_top_nav td.LC_top_nav_login {
 4659:   width: 4.0em;
 4660:   text-align: center;
 4661: }
 4662: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4663:   background: $tabbg;
 4664:   color: $font;
 4665:   font-family: $sans;
 4666:   font-size: smaller;
 4667: }
 4668: td.LC_table_cell_checkbox {
 4669:   text-align: center;
 4670: }
 4671: 
 4672: .LC_fontsize_small
 4673: {
 4674:  font-size: 70%;
 4675: }
 4676: 
 4677: .LC_fontsize_medium
 4678: {
 4679:  font-size: 85%;
 4680: }
 4681: 
 4682: .LC_fontsize_large
 4683: {
 4684:  font-size: 120%;
 4685: }
 4686: 
 4687: .LC_menubuttons_inline_text {
 4688:   color: $font;
 4689:   font-family: $sans;
 4690:   font-size: 90%;
 4691:   padding-left:3px;
 4692: }
 4693: 
 4694: .LC_menubuttons_link {
 4695:   text-decoration: none;
 4696: }
 4697: /*2008--9-5: new menu style sheet.Changed category*/
 4698: .LC_menubuttons_category {
 4699:   color: $font;
 4700:   background: $pgbg;
 4701:   font-family: $sans;
 4702:   font-size: larger;
 4703:   font-weight: bold;
 4704: }
 4705: 
 4706: td.LC_menubuttons_text {
 4707:  	color: $font; 	
 4708: }
 4709: 
 4710: 
 4711: 
 4712: .LC_current_location {
 4713:   font-family: $sans;
 4714:   background: $tabbg;
 4715: }
 4716: .LC_new_mail {
 4717:   font-family: $sans;
 4718:   background: $tabbg;
 4719:   font-weight: bold;
 4720: }
 4721: 
 4722: 
 4723: .LC_dropadd_labeltext {
 4724:   font-family: $sans;
 4725:   text-align: right;
 4726: }
 4727: 
 4728: .LC_preferences_labeltext {
 4729:   font-family: $sans;
 4730:   text-align: right;
 4731: }
 4732: 
 4733: .LC_roleslog_note {
 4734:   font-size: small;
 4735: }
 4736: 
 4737: .LC_mail_functions {
 4738:     font-weight: bold;
 4739: }
 4740: 
 4741: table.LC_aboutme_port {
 4742:   border: 0px;
 4743:   border-collapse: collapse;
 4744:   border-spacing: 0px;
 4745: }
 4746: table.LC_data_table, table.LC_mail_list {
 4747:   border: 1px solid #000000;
 4748:   border-collapse: separate;
 4749:   border-spacing: 1px;
 4750:   background: $pgbg;
 4751: }
 4752: .LC_data_table_dense {
 4753:   font-size: small;
 4754: }
 4755: table.LC_nested_outer {
 4756:   border: 1px solid #000000;
 4757:   border-collapse: collapse;
 4758:   border-spacing: 0px;
 4759:   width: 100%;
 4760: }
 4761: table.LC_nested {
 4762:   border: 0px;
 4763:   border-collapse: collapse;
 4764:   border-spacing: 0px;
 4765:   width: 100%;
 4766: }
 4767: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4768: table.LC_prior_tries tr th {
 4769:   font-weight: bold;
 4770:   background-color: $data_table_head;
 4771:   font-size:90%;
 4772: }
 4773: table.LC_data_table tr.LC_info_row > td {
 4774:   background-color: #CCCCCC;
 4775:   font-weight: bold;
 4776:   text-align: left;
 4777: }
 4778: table.LC_data_table tr.LC_odd_row > td, 
 4779: table.LC_pick_box tr > td.LC_odd_row,
 4780: table.LC_aboutme_port tr td {
 4781:   background-color: $data_table_light;
 4782:   padding: 2px;
 4783: }
 4784: table.LC_data_table tr.LC_even_row > td,
 4785: table.LC_pick_box tr > td.LC_even_row,
 4786: table.LC_aboutme_port tr.LC_even_row td {
 4787:   background-color: $data_table_dark;
 4788:   padding: 2px;
 4789: }
 4790: table.LC_data_table tr.LC_data_table_highlight td {
 4791:   background-color: $data_table_darker;
 4792: }
 4793: table.LC_data_table tr td.LC_leftcol_header {
 4794:   background-color: $data_table_head;
 4795:   font-weight: bold;
 4796: }
 4797: table.LC_data_table tr.LC_empty_row td,
 4798: table.LC_nested tr.LC_empty_row td {
 4799:   background-color: #FFFFFF;
 4800:   font-weight: bold;
 4801:   font-style: italic;
 4802:   text-align: center;
 4803:   padding: 8px;
 4804: }
 4805: table.LC_nested tr.LC_empty_row td {
 4806:   padding: 4ex
 4807: }
 4808: table.LC_nested_outer tr th {
 4809:   font-weight: bold;
 4810:   background-color: $data_table_head;
 4811:   font-size: small;
 4812:   border-bottom: 1px solid #000000;
 4813: }
 4814: table.LC_nested_outer tr td.LC_subheader {
 4815:   background-color: $data_table_head;
 4816:   font-weight: bold;
 4817:   font-size: small;
 4818:   border-bottom: 1px solid #000000;
 4819:   text-align: right;
 4820: }
 4821: table.LC_nested tr.LC_info_row td {
 4822:   background-color: #CCCCCC;
 4823:   font-weight: bold;
 4824:   font-size: small;
 4825:   text-align: center;
 4826: }
 4827: table.LC_nested tr.LC_info_row td.LC_left_item,
 4828: table.LC_nested_outer tr th.LC_left_item {
 4829:   text-align: left;
 4830: }
 4831: table.LC_nested td {
 4832:   background-color: #FFFFFF;
 4833:   font-size: small;
 4834: }
 4835: table.LC_nested_outer tr th.LC_right_item,
 4836: table.LC_nested tr.LC_info_row td.LC_right_item,
 4837: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4838: table.LC_nested tr td.LC_right_item {
 4839:   text-align: right;
 4840: }
 4841: 
 4842: table.LC_nested tr.LC_odd_row td {
 4843:   background-color: #EEEEEE;
 4844: }
 4845: 
 4846: table.LC_createuser {
 4847: }
 4848: 
 4849: table.LC_createuser tr.LC_section_row td {
 4850:   font-size: small;
 4851: }
 4852: 
 4853: table.LC_createuser tr.LC_info_row td  {
 4854:   background-color: #CCCCCC;
 4855:   font-weight: bold;
 4856:   text-align: center;
 4857: }
 4858: 
 4859: table.LC_calendar {
 4860:   border: 1px solid #000000;
 4861:   border-collapse: collapse;
 4862: }
 4863: table.LC_calendar_pickdate {
 4864:   font-size: xx-small;
 4865: }
 4866: table.LC_calendar tr td {
 4867:   border: 1px solid #000000;
 4868:   vertical-align: top;
 4869: }
 4870: table.LC_calendar tr td.LC_calendar_day_empty {
 4871:   background-color: $data_table_dark;
 4872: }
 4873: 
 4874: table.LC_mail_list tr.LC_mail_new {
 4875:   background-color: $mail_new;
 4876: }
 4877: table.LC_mail_list tr.LC_mail_new:hover {
 4878:   background-color: $mail_new_hover;
 4879: }
 4880: table.LC_mail_list tr.LC_mail_read {
 4881:   background-color: $mail_read;
 4882: }
 4883: table.LC_mail_list tr.LC_mail_read:hover {
 4884:   background-color: $mail_read_hover;
 4885: }
 4886: table.LC_mail_list tr.LC_mail_replied {
 4887:   background-color: $mail_replied;
 4888: }
 4889: table.LC_mail_list tr.LC_mail_replied:hover {
 4890:   background-color: $mail_replied_hover;
 4891: }
 4892: table.LC_mail_list tr.LC_mail_other {
 4893:   background-color: $mail_other;
 4894: }
 4895: table.LC_mail_list tr.LC_mail_other:hover {
 4896:   background-color: $mail_other_hover;
 4897: }
 4898: 
 4899: table.LC_data_table tr > td.LC_browser_file {
 4900:   background: #CCFF88;
 4901: }
 4902: table.LC_data_table tr > td.LC_browser_file_locked {
 4903:   background: #FFAA99;
 4904: }
 4905: table.LC_data_table tr.LC_browser_folder > td {
 4906:   background: #CCCCFF;
 4907: }
 4908: 
 4909: table.LC_data_table tr > td.LC_roles_is {
 4910: /*  background: #77FF77; */
 4911: }
 4912: table.LC_data_table tr > td.LC_roles_future {
 4913:   background: #FFFF77;
 4914: }
 4915: table.LC_data_table tr > td.LC_roles_will {
 4916:   background: #FFAA77;
 4917: }
 4918: table.LC_data_table tr > td.LC_roles_expired {
 4919:   background: #FF7777;
 4920: }
 4921: table.LC_data_table tr > td.LC_roles_will_not {
 4922:   background: #AAFF77;
 4923: }
 4924: table.LC_data_table tr > td.LC_roles_selected {
 4925:   background: #11CC55;
 4926: }
 4927: 
 4928: span.LC_current_location {
 4929:   font-size:larger;
 4930:   background: $pgbg;
 4931: }
 4932: 
 4933: span.LC_parm_menu_item {
 4934:   font-size: larger;
 4935:   font-family: $sans;
 4936: }
 4937: span.LC_parm_scope_all {
 4938:   color: red;
 4939: }
 4940: span.LC_parm_scope_folder {
 4941:   color: green;
 4942: }
 4943: span.LC_parm_scope_resource {
 4944:   color: orange;
 4945: }
 4946: span.LC_parm_part {
 4947:   color: blue;
 4948: }
 4949: span.LC_parm_folder, span.LC_parm_symb {
 4950:   font-size: x-small;
 4951:   font-family: $mono;
 4952:   color: #AAAAAA;
 4953: }
 4954: 
 4955: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4956: td.LC_parm_overview_parm_selectors {
 4957:   border: 1px solid black;
 4958:   border-collapse: collapse;
 4959: }
 4960: table.LC_parm_overview_restrictions td {
 4961:   border-width: 1px 4px 1px 4px;
 4962:   border-style: solid;
 4963:   border-color: $pgbg;
 4964:   text-align: center;
 4965: }
 4966: table.LC_parm_overview_restrictions th {
 4967:   background: $tabbg;
 4968:   border-width: 1px 4px 1px 4px;
 4969:   border-style: solid;
 4970:   border-color: $pgbg;
 4971: }
 4972: table#LC_helpmenu {
 4973:   border: 0px;
 4974:   height: 55px;
 4975:   border-spacing: 0px;
 4976: }
 4977: 
 4978: table#LC_helpmenu fieldset legend {
 4979:   font-size: larger;
 4980:   font-weight: bold;
 4981: }
 4982: table#LC_helpmenu_links {
 4983:   width: 100%;
 4984:   border: 1px solid black;
 4985:   background: $pgbg;
 4986:   padding: 0px;
 4987:   border-spacing: 1px;
 4988: }
 4989: table#LC_helpmenu_links tr td {
 4990:   padding: 1px;
 4991:   background: $tabbg;
 4992:   text-align: center;
 4993:   font-weight: bold;
 4994: }
 4995: 
 4996: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 4997: table#LC_helpmenu_links a:active {
 4998:   text-decoration: none;
 4999:   color: $font;
 5000: }
 5001: table#LC_helpmenu_links a:hover {
 5002:   text-decoration: underline;
 5003:   color: $vlink;
 5004: }
 5005: 
 5006: .LC_chrt_popup_exists {
 5007:   border: 1px solid #339933;
 5008:   margin: -1px;
 5009: }
 5010: .LC_chrt_popup_up {
 5011:   border: 1px solid yellow;
 5012:   margin: -1px;
 5013: }
 5014: .LC_chrt_popup {
 5015:   border: 1px solid #8888FF;
 5016:   background: #CCCCFF;
 5017: }
 5018: table.LC_pick_box {
 5019:   border-collapse: separate;
 5020:   background: white;
 5021:   border: 1px solid black;
 5022:   border-spacing: 1px;
 5023: }
 5024: table.LC_pick_box td.LC_pick_box_title {
 5025:   background: $tabbg;
 5026:   font-weight: bold;
 5027:   text-align: right;
 5028:   vertical-align: top;
 5029:   width: 184px;
 5030:   padding: 8px;
 5031: }
 5032: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5033:   background: $tabbg;
 5034:   font-weight: bold;
 5035:   text-align: right;
 5036:   width: 350px;
 5037:   padding: 8px;
 5038: }
 5039: 
 5040: table.LC_pick_box td.LC_pick_box_value {
 5041:   text-align: left;
 5042:   padding: 8px;
 5043: }
 5044: table.LC_pick_box td.LC_pick_box_select {
 5045:   text-align: left;
 5046:   padding: 8px;
 5047: }
 5048: table.LC_pick_box td.LC_pick_box_separator {
 5049:   padding: 0px;
 5050:   height: 1px;
 5051:   background: black;
 5052: }
 5053: table.LC_pick_box td.LC_pick_box_submit {
 5054:   text-align: right;
 5055: }
 5056: table.LC_pick_box td.LC_evenrow_value {
 5057:   text-align: left;
 5058:   padding: 8px;
 5059:   background-color: $data_table_light;
 5060: }
 5061: table.LC_pick_box td.LC_oddrow_value {
 5062:   text-align: left;
 5063:   padding: 8px;
 5064:   background-color: $data_table_light;
 5065: }
 5066: table.LC_helpform_receipt {
 5067:   width: 620px;
 5068:   border-collapse: separate;
 5069:   background: white;
 5070:   border: 1px solid black;
 5071:   border-spacing: 1px;
 5072: }
 5073: table.LC_helpform_receipt td.LC_pick_box_title {
 5074:   background: $tabbg;
 5075:   font-weight: bold;
 5076:   text-align: right;
 5077:   width: 184px;
 5078:   padding: 8px;
 5079: }
 5080: table.LC_helpform_receipt td.LC_evenrow_value {
 5081:   text-align: left;
 5082:   padding: 8px;
 5083:   background-color: $data_table_light;
 5084: }
 5085: table.LC_helpform_receipt td.LC_oddrow_value {
 5086:   text-align: left;
 5087:   padding: 8px;
 5088:   background-color: $data_table_light;
 5089: }
 5090: table.LC_helpform_receipt td.LC_pick_box_separator {
 5091:   padding: 0px;
 5092:   height: 1px;
 5093:   background: black;
 5094: }
 5095: span.LC_helpform_receipt_cat {
 5096:   font-weight: bold;
 5097: }
 5098: table.LC_group_priv_box {
 5099:   background: white;
 5100:   border: 1px solid black;
 5101:   border-spacing: 1px;
 5102: }
 5103: table.LC_group_priv_box td.LC_pick_box_title {
 5104:   background: $tabbg;
 5105:   font-weight: bold;
 5106:   text-align: right;
 5107:   width: 184px;
 5108: }
 5109: table.LC_group_priv_box td.LC_groups_fixed {
 5110:   background: $data_table_light;
 5111:   text-align: center;
 5112: }
 5113: table.LC_group_priv_box td.LC_groups_optional {
 5114:   background: $data_table_dark;
 5115:   text-align: center;
 5116: }
 5117: table.LC_group_priv_box td.LC_groups_functionality {
 5118:   background: $data_table_darker;
 5119:   text-align: center;
 5120:   font-weight: bold;
 5121: }
 5122: table.LC_group_priv td {
 5123:   text-align: left;
 5124:   padding: 0px;
 5125: }
 5126: 
 5127: table.LC_notify_front_page {
 5128:   background: white;
 5129:   border: 1px solid black;
 5130:   padding: 8px;
 5131: }
 5132: table.LC_notify_front_page td {
 5133:   padding: 8px;
 5134: }
 5135: .LC_navbuttons {
 5136:   margin: 2ex 0ex 2ex 0ex;
 5137: }
 5138: .LC_topic_bar {
 5139:   font-family: $sans;
 5140:   font-weight: bold;
 5141:   width: 100%;
 5142:   background: $tabbg;
 5143:   vertical-align: middle;
 5144:   margin: 2ex 0ex 2ex 0ex;
 5145: }
 5146: .LC_topic_bar span {
 5147:   vertical-align: middle;
 5148: }
 5149: .LC_topic_bar img {
 5150:   vertical-align: bottom;
 5151: }
 5152: table.LC_course_group_status {
 5153:   margin: 20px;
 5154: }
 5155: table.LC_status_selector td {
 5156:   vertical-align: top;
 5157:   text-align: center;
 5158:   padding: 4px;
 5159: }
 5160: table.LC_descriptive_input td.LC_description {
 5161:   vertical-align: top;
 5162:   text-align: right;
 5163:   font-weight: bold;
 5164: }
 5165: div.LC_feedback_link {
 5166:   clear: both;
 5167:   background: white;
 5168:   width: 100%;  
 5169: }
 5170: span.LC_feedback_link {
 5171:   background: $feedback_link_bg;
 5172:   font-size: larger;
 5173: }
 5174: span.LC_message_link {
 5175:   background: $feedback_link_bg;
 5176:   font-size: larger;
 5177:   position: absolute;
 5178:   right: 1em;
 5179: }
 5180: 
 5181: table.LC_prior_tries {
 5182:   border: 1px solid #000000;
 5183:   border-collapse: separate;
 5184:   border-spacing: 1px;
 5185: }
 5186: 
 5187: table.LC_prior_tries td {
 5188:   padding: 2px;
 5189: }
 5190: 
 5191: .LC_answer_correct {
 5192:   background: #AAFFAA;
 5193:   color: black;
 5194: }
 5195: .LC_answer_charged_try {
 5196:   background: #FFAAAA ! important;
 5197:   color: black;
 5198: }
 5199: .LC_answer_not_charged_try, 
 5200: .LC_answer_no_grade,
 5201: .LC_answer_late {
 5202:   background: #FFFFAA;
 5203:   color: black;
 5204: }
 5205: .LC_answer_previous {
 5206:   background: #AAAAFF;
 5207:   color: black;
 5208: }
 5209: 
 5210: 
 5211: span.LC_prior_numerical,
 5212: span.LC_prior_string,
 5213: span.LC_prior_custom,
 5214: span.LC_prior_reaction,
 5215: span.LC_prior_math {
 5216:   font-family: monospace;
 5217:   white-space: pre;
 5218: }
 5219: 
 5220: span.LC_prior_string {
 5221:   font-family: monospace;
 5222:   white-space: pre;
 5223: }
 5224: 
 5225: table.LC_prior_option {
 5226:   width: 100%;
 5227:   border-collapse: collapse;
 5228: }
 5229: table.LC_prior_rank, table.LC_prior_match {
 5230:   border-collapse: collapse;
 5231: }
 5232: table.LC_prior_option tr td,
 5233: table.LC_prior_rank tr td,
 5234: table.LC_prior_match tr td {
 5235:   border: 1px solid #000000;
 5236: }
 5237: 
 5238: td.LC_nobreak,
 5239: span.LC_nobreak {
 5240:   white-space: nowrap;
 5241: }
 5242: 
 5243: span.LC_cusr_emph {
 5244:   font-style: italic;
 5245: }
 5246: 
 5247: span.LC_cusr_subheading {
 5248:   font-weight: normal;
 5249:   font-size: 85%;
 5250: }
 5251: 
 5252: table.LC_docs_documents {
 5253:   background: #BBBBBB;
 5254:   border-width: 0px;
 5255:   border-collapse: collapse;
 5256: }
 5257: 
 5258: .LC_docs_entry_move {
 5259:   border: 0px;
 5260:   border-collapse: collapse;
 5261: }
 5262: 
 5263: .LC_docs_entry_move td {
 5264:   border: 2px solid #BBBBBB;
 5265:   background: #DDDDDD;
 5266: }
 5267: 
 5268: .LC_docs_editor td.LC_docs_entry_commands {
 5269:   background: #DDDDDD;
 5270:   font-size: x-small;
 5271: }
 5272: .LC_docs_copy {
 5273:   color: #000099;
 5274: }
 5275: .LC_docs_cut {
 5276:   color: #550044;
 5277: }
 5278: .LC_docs_rename {
 5279:   color: #009900;
 5280: }
 5281: .LC_docs_remove {
 5282:   color: #990000;
 5283: }
 5284: 
 5285: .LC_docs_reinit_warn,
 5286: .LC_docs_ext_edit {
 5287:   font-size: x-small;
 5288: }
 5289: 
 5290: .LC_docs_editor td.LC_docs_entry_title,
 5291: .LC_docs_editor td.LC_docs_entry_icon {
 5292:   background: #FFFFBB;
 5293: }
 5294: .LC_docs_editor td.LC_docs_entry_parameter {
 5295:   background: #BBBBFF;
 5296:   font-size: x-small;
 5297:   white-space: nowrap;
 5298: }
 5299: 
 5300: table.LC_docs_adddocs td,
 5301: table.LC_docs_adddocs th {
 5302:   border: 1px solid #BBBBBB;
 5303:   padding: 4px;
 5304:   background: #DDDDDD;
 5305: }
 5306: 
 5307: table.LC_sty_begin {
 5308:   background: #BBFFBB;
 5309: }
 5310: table.LC_sty_end {
 5311:   background: #FFBBBB;
 5312: }
 5313: 
 5314: table.LC_double_column {
 5315:   border-width: 0px;
 5316:   border-collapse: collapse;
 5317:   width: 100%;
 5318:   padding: 2px;
 5319: }
 5320: 
 5321: table.LC_double_column tr td.LC_left_col {
 5322:   top: 2px;
 5323:   left: 2px;
 5324:   width: 47%;
 5325:   vertical-align: top;
 5326: }
 5327: 
 5328: table.LC_double_column tr td.LC_right_col {
 5329:   top: 2px;
 5330:   right: 2px; 
 5331:   width: 47%;
 5332:   vertical-align: top;
 5333: }
 5334: 
 5335: span.LC_role_level {
 5336:   font-weight: bold;
 5337: }
 5338: 
 5339: div.LC_left_float {
 5340:   float: left;
 5341:   padding-right: 5%;
 5342:   padding-bottom: 4px;
 5343: }
 5344: 
 5345: div.LC_clear_float_header {
 5346:   padding-bottom: 2px;
 5347: }
 5348: 
 5349: div.LC_clear_float_footer {
 5350:   padding-top: 10px;
 5351:   clear: both;
 5352: }
 5353: 
 5354: 
 5355: div.LC_grade_show_user {
 5356:   margin-top: 20px;
 5357:   border: 1px solid black;
 5358: }
 5359: div.LC_grade_user_name {
 5360:   background: #DDDDEE;
 5361:   border-bottom: 1px solid black;
 5362:   font-weight: bold;
 5363:   font-size: large;
 5364: }
 5365: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5366:   background: #DDEEDD;
 5367: }
 5368: 
 5369: div.LC_grade_show_problem,
 5370: div.LC_grade_submissions,
 5371: div.LC_grade_message_center,
 5372: div.LC_grade_info_links,
 5373: div.LC_grade_assign {
 5374:   margin: 5px;
 5375:   width: 99%;
 5376:   background: #FFFFFF;
 5377: }
 5378: div.LC_grade_show_problem_header,
 5379: div.LC_grade_submissions_header,
 5380: div.LC_grade_message_center_header,
 5381: div.LC_grade_assign_header {
 5382:   font-weight: bold;
 5383:   font-size: large;
 5384: }
 5385: div.LC_grade_show_problem_problem,
 5386: div.LC_grade_submissions_body,
 5387: div.LC_grade_message_center_body,
 5388: div.LC_grade_assign_body {
 5389:   border: 1px solid black;
 5390:   width: 99%;
 5391:   background: #FFFFFF;
 5392: }
 5393: span.LC_grade_check_note {
 5394:   font-weight: normal;
 5395:   font-size: medium;
 5396:   display: inline;
 5397:   position: absolute;
 5398:   right: 1em;
 5399: }
 5400: 
 5401: table.LC_scantron_action {
 5402:   width: 100%;
 5403: }
 5404: table.LC_scantron_action tr th {
 5405:   font-weight:bold;
 5406:   font-style:normal;
 5407: }
 5408: .LC_edit_problem_header, 
 5409: div.LC_edit_problem_footer {
 5410:   font-weight: normal;
 5411:   font-size:  medium;
 5412:   margin: 2px;
 5413: }
 5414: div.LC_edit_problem_header,
 5415: div.LC_edit_problem_header div,
 5416: div.LC_edit_problem_footer,
 5417: div.LC_edit_problem_footer div,
 5418: div.LC_edit_problem_editxml_header,
 5419: div.LC_edit_problem_editxml_header div {
 5420:   margin-top: 5px;
 5421: }
 5422: div.LC_edit_problem_header_edit_row {
 5423:   background: $tabbg;
 5424:   padding: 3px;
 5425:   margin-bottom: 5px;
 5426: }
 5427: div.LC_edit_problem_header_title {
 5428:   font-weight: bold;
 5429:   font-size: larger;
 5430:   background: $tabbg;
 5431:   padding: 3px;
 5432: }
 5433: table.LC_edit_problem_header_title {
 5434:   font-size: larger;
 5435:   font-weight:  bold;
 5436:   width: 100%;
 5437:   border-color: $pgbg;
 5438:   border-style: solid;
 5439:   border-width: $border;
 5440: 
 5441:   background: $tabbg;
 5442:   border-collapse: collapse;
 5443:   padding: 0px
 5444: }
 5445: 
 5446: div.LC_edit_problem_discards {
 5447:   float: left;
 5448:   padding-bottom: 5px;
 5449: }
 5450: div.LC_edit_problem_saves {
 5451:   float: right;
 5452:   padding-bottom: 5px;
 5453: }
 5454: hr.LC_edit_problem_divide {
 5455:   clear: both;
 5456:   color: $tabbg;
 5457:   background-color: $tabbg;
 5458:   height: 3px;
 5459:   border: 0px;
 5460: }
 5461: img.stift{
 5462:   border-width:0;
 5463:   vertical-align:middle;
 5464: }
 5465: 
 5466: table#LC_mainmenu{
 5467:  margin-top:10px;
 5468:  width:80%;
 5469: 
 5470: }
 5471: 
 5472: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5473:   vertical-align: top;
 5474:   width: 45%;
 5475: }
 5476: 
 5477: div.LC_createcourse {
 5478:     margin: 10px 10px 10px 10px;
 5479: }
 5480: 
 5481: /* ---- Remove when done ----
 5482: # The following styles is part of the redesign of LON-CAPA and are
 5483: # subject to change during this project.
 5484: # Don't rely on their current functionality as they might be 
 5485: # changed or removed.
 5486: # --------------------------*/
 5487: 
 5488: a:hover,
 5489: ol.LC_smallMenu a:hover,
 5490: ol#LC_MenuBreadcrumbs a:hover,
 5491: ol#LC_PathBreadcrumbs a:hover,
 5492: ul#LC_TabMainMenuContent a:hover,
 5493: .LC_FormSectionClearButton input:hover
 5494: ul.LC_TabContent   li:hover a{
 5495: 	color:#BF2317;
 5496:         text-decoration:none;
 5497: }
 5498: 
 5499: h1 { 
 5500: 	padding:5px 10px 5px 20px;
 5501: 	line-height:130%;
 5502: }
 5503: 
 5504: h2,h3,h4,h5,h6
 5505: {
 5506: 	margin:5px 0px 5px 0px;
 5507: 	padding:0px;
 5508: 	line-height:130%;
 5509: }
 5510: .LC_hcell{
 5511:         padding:3px 15px 3px 15px;
 5512:         margin:0px;
 5513: 	background-color:$tabbg;
 5514: 	border-bottom:solid 1px $lg_border_color;       
 5515: }
 5516: .LC_noBorder {
 5517:         border:0px;
 5518: }
 5519: 
 5520: 
 5521: /* Main Header with discription of Person, Course, etc. */
 5522: 
 5523: .LC_Right {
 5524:         float: right;
 5525:         margin: 0px;
 5526:         padding: 0px;
 5527: }
 5528: 
 5529: p, .LC_ContentBox {
 5530: 	padding: 10px;
 5531: 
 5532: }
 5533: .LC_FormSectionClearButton input {
 5534:         background-color:transparent;    	    
 5535:         border:0px;
 5536:         cursor:pointer;
 5537:         text-decoration:underline;
 5538: }
 5539: 
 5540: .LC_help_open_topic {
 5541:         color: #FFFFFF;
 5542:         background-color: #EEEEFF;
 5543:         margin: 1px;
 5544:         padding: 4px;
 5545:         border: 1px solid #000033;
 5546:         white-space: nowrap;
 5547: }
 5548: 
 5549: dl,ul,div,fieldset {
 5550: 	margin: 10px 10px 10px 0px;
 5551: 	overflow:hidden;
 5552: }
 5553: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5554: 	margin: 0px;
 5555: }
 5556: 
 5557: ol.LC_smallMenu li {
 5558: 	display: inline;
 5559: 	padding: 5px 5px 0px 10px;
 5560: 	vertical-align: top;
 5561: }
 5562: 
 5563: ol.LC_smallMenu li img {
 5564: 	vertical-align: bottom;
 5565: }
 5566: 
 5567: ol.LC_smallMenu a {
 5568: 	font-size: 90%;
 5569: 	color: RGB(80, 80, 80);
 5570: 	text-decoration: none;
 5571: }
 5572: ol#LC_TabMainMenuContent, ul.LC_TabContent ,
 5573: ul.LC_TabContentBigger {
 5574: 	display:block;
 5575: 	list-style:none;
 5576: 	margin: 0px;
 5577: 	padding: 0px;
 5578: }
 5579: 
 5580: ol#LC_TabMainMenuContent li, ul.LC_TabContent li,
 5581: ul.LC_TabContentBigger li{
 5582: 	display: inline;
 5583: 	border-right: solid 1px $lg_border_color;
 5584: 	float:left;
 5585: 	line-height:140%;
 5586: 	white-space:nowrap;
 5587: }
 5588: ol#LC_TabMainMenuContent li{
 5589: 	vertical-align: bottom;
 5590: 	border-bottom: solid 1px RGB(175, 175, 175);
 5591: 	padding: 5px 10px 5px 10px;
 5592: 	margin-right:5px;
 5593: 	margin-bottom:3px;
 5594: 	font-weight: bold;
 5595: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5596: }
 5597: 
 5598: ol#LC_TabMainMenuContent li a{
 5599: 	color: RGB(47, 47, 47);
 5600: 	text-decoration: none;
 5601: }
 5602: ul.LC_TabContent {
 5603: 	min-height:1.6em;
 5604: }
 5605: ul.LC_TabContent li{
 5606: 	vertical-align:middle;
 5607: 	padding:0px 10px 0px 10px;
 5608: 	background-color:$tabbg;
 5609: 	border-bottom:solid 1px $lg_border_color;
 5610: }
 5611: ul.LC_TabContent li a, ul.LC_TabContent li{ 
 5612: 	color:rgb(47,47,47);
 5613: 	text-decoration:none;
 5614: 	font-size:95%;
 5615: 	font-weight:bold;
 5616: 	padding-right: 16px;
 5617: }
 5618: ul.LC_TabContent li:hover, ul.LC_TabContent li.active{
 5619:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5620: 	border-bottom:solid 1px #FFFFFF;
 5621: 	padding-right: 16px;
 5622: }
 5623: ul.LC_TabContentBigger li{
 5624: 	vertical-align:bottom;
 5625: 	border-top:solid 1px $lg_border_color;
 5626: 	border-left:solid 1px $lg_border_color;
 5627: 	padding:5px 10px 5px 10px;
 5628: 	margin-left:2px;
 5629: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5630: }
 5631: ul.LC_TabContentBigger li:hover, ul.LC_TabContentBigger li.active{
 5632: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5633: }
 5634: ul.LC_TabContentBigger li, ul.LC_TabContentBigger li a{
 5635: 	font-size:110%;
 5636: 	font-weight:bold;
 5637: }
 5638: 
 5639: ol#LC_MenuBreadcrumbs, ol#LC_PathBreadcrumbs {
 5640: 	border-top: solid 1px RGB(255, 255, 255);
 5641: 	height: 20px;
 5642: 	line-height: 20px;
 5643: 	vertical-align: bottom;
 5644: 	margin: 0px 0px 30px 0px;
 5645: 	padding-left: 10px;
 5646: 	list-style-position: inside;
 5647: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5648: }
 5649: 
 5650: ol#LC_MenuBreadcrumbs li, ol#LC_PathBreadcrumbs li {
 5651: /*
 5652: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5653: */	
 5654: 	display: inline;
 5655: 	padding: 0px 0px 0px 10px;
 5656: 	vertical-align: bottom;
 5657: 	overflow:hidden;
 5658: }
 5659: 
 5660: ol#LC_MenuBreadcrumbs li a {
 5661: 	text-decoration: none;
 5662: 	font-size:90%;
 5663: }
 5664: ol#LC_PathBreadcrumbs li a{
 5665: 	text-decoration:none;
 5666: 	font-size:100%;
 5667: 	font-weight:bold;
 5668: }
 5669: .LC_ContentBoxSpecial
 5670: {
 5671: 	border: solid 1px $lg_border_color;
 5672: }
 5673: .LC_ContentBoxSpecialContactInfo
 5674: {
 5675: 	border: solid 1px $lg_border_color;
 5676: 	max-width:25%;
 5677: 	min-width:25%;
 5678: }
 5679: .LC_AboutMe_Image
 5680: {
 5681: 	float:left;
 5682: 	margin-right:10px;
 5683: }
 5684: .LC_Clear_AboutMe_Image
 5685: {
 5686: 	clear:left;
 5687: }
 5688: dl.LC_ListStyleClean dt {
 5689: 	padding-right: 5px;
 5690: 	display: table-header-group;
 5691: }
 5692: 
 5693: dl.LC_ListStyleClean dd {
 5694: 	display: table-row;
 5695: }
 5696: 
 5697: .LC_ListStyleClean,
 5698: .LC_ListStyleSimple,
 5699: .LC_ListStyleNormal,
 5700: .LC_ListStyleSpecial
 5701: 	{
 5702: 	/*display:block;	*/
 5703: 	list-style-position: inside;
 5704: 	list-style-type: none;
 5705: 	overflow: hidden;
 5706: 	padding: 0px;
 5707: }
 5708: 
 5709: .LC_ListStyleSimple li,
 5710: .LC_ListStyleSimple dd,
 5711: .LC_ListStyleNormal li,
 5712: .LC_ListStyleNormal dd,
 5713: .LC_ListStyleSpecial li,
 5714: .LC_ListStyleSpecial dd
 5715: 	{
 5716: 	margin: 0px;
 5717: 	padding: 5px 5px 5px 10px;
 5718: 	clear: both;
 5719: }
 5720: 
 5721: .LC_ListStyleClean li,
 5722: .LC_ListStyleClean dd {
 5723: 	padding-top: 0px;
 5724: 	padding-bottom: 0px;
 5725: }
 5726: 
 5727: .LC_ListStyleSimple dd,
 5728: .LC_ListStyleSimple li{
 5729: 	border-bottom: solid 1px $lg_border_color;
 5730: }
 5731: 
 5732: .LC_ListStyleSpecial li,
 5733: .LC_ListStyleSpecial dd {
 5734: 	list-style-type: none;
 5735: 	background-color: RGB(220, 220, 220);
 5736: 	margin-bottom: 4px;
 5737: }
 5738: 
 5739: table.LC_SimpleTable {
 5740: 	margin:5px;
 5741: 	border:solid 1px $lg_border_color;
 5742: 	}
 5743: 
 5744: table.LC_SimpleTable tr {
 5745: 	padding:0px;
 5746: 	border:solid 1px $lg_border_color;
 5747: }
 5748: table.LC_SimpleTable thead{
 5749: 	 background:rgb(220,220,220);
 5750: }
 5751: 
 5752: div.LC_columnSection {
 5753: 	display: block;
 5754: 	clear: both;
 5755: 	overflow: hidden;
 5756: 	margin:0px;
 5757: }
 5758: 
 5759: div.LC_columnSection>* {
 5760: 	float: left;
 5761: 	margin: 10px 20px 10px 0px;
 5762: 	overflow:hidden;
 5763: }
 5764: 
 5765: .ContentBoxSpecialTemplate
 5766: {
 5767:         border: solid 1px $lg_border_color;
 5768: }
 5769: .ContentBoxTemplate {
 5770:         padding:10px;
 5771: }
 5772: 
 5773: div.LC_columnSection > .ContentBoxTemplate,
 5774: div.LC_columnSection > .ContentBoxSpecialTemplate
 5775:         {
 5776:         width: 600px;
 5777: }
 5778: 
 5779: .clear{
 5780: 	clear: both;
 5781: 	line-height: 0px;
 5782: 	font-size: 0px;
 5783: 	height: 0px;
 5784: }
 5785: 
 5786: .LC_loginpage_container {
 5787: 	text-align:left;
 5788: 	margin : 0 auto;
 5789: 	width:65%;
 5790: 	padding: 10px;
 5791: 	height: auto;
 5792: 	background-color:#FFFFFF;
 5793: 	border:1px solid #CCCCCC;
 5794: }
 5795: 
 5796: 
 5797: .LC_loginpage_loginContainer {
 5798: 	float:left;
 5799: 	width: 182px;
 5800: 	border:1px solid #CCCCCC;
 5801: 	background-color:$loginbg;
 5802: }
 5803: 
 5804: .LC_loginpage_loginContainer h2{
 5805: 	margin-top:0;
 5806: 	display:block;
 5807: 	background:$bgcol;
 5808: 	color:$textcol;
 5809: 	padding-left:5px;
 5810: }
 5811: .LC_loginpage_loginInfo {
 5812: 	margin-left:20px;
 5813: 	float:left;
 5814: 	width:30%;
 5815: 	border:1px solid #CCCCCC;
 5816: 	padding:10px;
 5817: }
 5818: 
 5819: .LC_loginpage_loginDomain {
 5820: 	margin-right:20px;
 5821: 	width:20%;
 5822: 	float:left;
 5823: 	padding:10px;
 5824: }
 5825: 
 5826: .LC_loginpage_space {
 5827: 	clear: both;
 5828: 	margin-bottom: 20px;
 5829: 	border-bottom: 1px solid #CCCCCC;
 5830: }
 5831: 
 5832: table em{
 5833: 	font-weight: bold;
 5834: 	font-style: normal;
 5835: }
 5836: table.LC_tableBrowseRes, 
 5837: table.LC_tableOfContent{
 5838:         border:none;
 5839: 	border-spacing: 1;
 5840: 	padding: 3px;
 5841: 	background-color: #FFFFFF;
 5842: 	font-size: 90%;
 5843: }
 5844: table.LC_tableBrowseRes a,
 5845: table.LC_tableOfContent a {
 5846:         background-color: transparent;
 5847: 	text-decoration: none;
 5848: }
 5849: 
 5850: table.LC_tableBrowseRes tr.LC_trOdd,
 5851: table.LC_tableOfContent tr.LC_trOdd{
 5852: 	background-color: #EEEEEE;
 5853: }
 5854: 
 5855: table.LC_tableOfContent img{
 5856: 	border: none;
 5857: 	height: 1.3em;
 5858: 	vertical-align: text-bottom;
 5859: 	margin-right: 0.3em;
 5860: }
 5861: 
 5862: a#LC_content_toolbar_firsthomework{
 5863: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 5864: }
 5865: 
 5866: a#LC_content_toolbar_launchnav{
 5867: 	background-image:url(/res/adm/pages/start-navigation.gif);
 5868: }
 5869: 
 5870: a#LC_content_toolbar_closenav{
 5871: 	background-image:url(/res/adm/pages/close-navigation.gif);
 5872: }
 5873: 
 5874: a#LC_content_toolbar_everything{
 5875: 	background-image:url(/res/adm/pages/show-all.gif);
 5876: }
 5877: 
 5878: a#LC_content_toolbar_uncompleted{
 5879: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 5880: }
 5881: 
 5882: #LC_content_toolbar_clearbubbles{
 5883: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 5884: }
 5885: 
 5886: a#LC_content_toolbar_changefolder{
 5887: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 5888: }
 5889: 
 5890: a#LC_content_toolbar_changefolder_toggled{
 5891: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 5892: }
 5893: 
 5894: ul#LC_toolbar li a:hover{
 5895: 	background-position: bottom center;
 5896: }
 5897: 
 5898: ul#LC_toolbar{
 5899: 	padding:0; 
 5900: 	margin: 2px;
 5901: 	list-style:none;
 5902: 	position:relative;
 5903: 	background-color:white;
 5904: }
 5905: 
 5906: ul#LC_toolbar li{
 5907: 	border:1px solid white;
 5908: 	padding:0;
 5909: 	margin: 0;
 5910:     float: left;
 5911: 	display:inline;
 5912: 	vertical-align:middle;
 5913: }
 5914: 
 5915: a.LC_toolbarItem{
 5916: 	display:block;
 5917: 	padding:0;
 5918: 	margin:0;
 5919: 	height: 32px;
 5920: 	width: 32px;
 5921: 	color:white; 
 5922: 	border:0 none;	
 5923: 	background-repeat:no-repeat;
 5924: 	background-color:transparent;
 5925: }
 5926: 
 5927: 
 5928: END
 5929: }
 5930: 
 5931: =pod
 5932: 
 5933: =item * &headtag()
 5934: 
 5935: Returns a uniform footer for LON-CAPA web pages.
 5936: 
 5937: Inputs: $title - optional title for the head
 5938:         $head_extra - optional extra HTML to put inside the <head>
 5939:         $args - optional arguments
 5940:             force_register - if is true call registerurl so the remote is 
 5941:                              informed
 5942:             redirect       -> array ref of
 5943:                                    1- seconds before redirect occurs
 5944:                                    2- url to redirect to
 5945:                                    3- whether the side effect should occur
 5946:                            (side effect of setting 
 5947:                                $env{'internal.head.redirect'} to the url 
 5948:                                redirected too)
 5949:             domain         -> force to color decorate a page for a specific
 5950:                                domain
 5951:             function       -> force usage of a specific rolish color scheme
 5952:             bgcolor        -> override the default page bgcolor
 5953:             no_auto_mt_title
 5954:                            -> prevent &mt()ing the title arg
 5955: 
 5956: =cut
 5957: 
 5958: sub headtag {
 5959:     my ($title,$head_extra,$args) = @_;
 5960:     
 5961:     my $function = $args->{'function'} || &get_users_function();
 5962:     my $domain   = $args->{'domain'}   || &determinedomain();
 5963:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5964:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5965: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5966: 		   #time(),
 5967: 		   $env{'environment.color.timestamp'},
 5968: 		   $function,$domain,$bgcolor);
 5969: 
 5970:     $url = '/adm/css/'.&escape($url).'.css';
 5971: 
 5972:     my $result =
 5973: 	'<head>'.
 5974: 	&font_settings();
 5975: 
 5976:     if (!$args->{'frameset'}) {
 5977: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5978:     }
 5979:     if ($args->{'force_register'}) {
 5980: 	$result .= &Apache::lonmenu::registerurl(1);
 5981:     }
 5982:     if (!$args->{'no_nav_bar'} 
 5983: 	&& !$args->{'only_body'}
 5984: 	&& !$args->{'frameset'}) {
 5985: 	$result .= &help_menu_js();
 5986:     }
 5987: 
 5988:     if (ref($args->{'redirect'})) {
 5989: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5990: 	$url = &Apache::lonenc::check_encrypt($url);
 5991: 	if (!$inhibit_continue) {
 5992: 	    $env{'internal.head.redirect'} = $url;
 5993: 	}
 5994: 	$result.=<<ADDMETA
 5995: <meta http-equiv="pragma" content="no-cache" />
 5996: <meta http-equiv="Refresh" content="$time; url=$url" />
 5997: ADDMETA
 5998:     }
 5999:     if (!defined($title)) {
 6000: 	$title = 'The LearningOnline Network with CAPA';
 6001:     }
 6002:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6003:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6004: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6005: 	.$head_extra;
 6006:     return $result;
 6007: }
 6008: 
 6009: =pod
 6010: 
 6011: =item * &font_settings()
 6012: 
 6013: Returns neccessary <meta> to set the proper encoding
 6014: 
 6015: Inputs: none
 6016: 
 6017: =cut
 6018: 
 6019: sub font_settings {
 6020:     my $headerstring='';
 6021:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6022: 	$headerstring.=
 6023: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6024:     }
 6025:     return $headerstring;
 6026: }
 6027: 
 6028: =pod
 6029: 
 6030: =item * &xml_begin()
 6031: 
 6032: Returns the needed doctype and <html>
 6033: 
 6034: Inputs: none
 6035: 
 6036: =cut
 6037: 
 6038: sub xml_begin {
 6039:     my $output='';
 6040: 
 6041:     if ($env{'internal.start_page'}==1) {
 6042: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6043:     }
 6044: 
 6045:     if ($env{'browser.mathml'}) {
 6046: 	$output='<?xml version="1.0"?>'
 6047:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6048: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6049:             
 6050: #	    .'<!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">] >'
 6051: 	    .'<!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">'
 6052:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6053: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6054:     } else {
 6055: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6056:     }
 6057:     return $output;
 6058: }
 6059: 
 6060: =pod
 6061: 
 6062: =item * &endheadtag()
 6063: 
 6064: Returns a uniform </head> for LON-CAPA web pages.
 6065: 
 6066: Inputs: none
 6067: 
 6068: =cut
 6069: 
 6070: sub endheadtag {
 6071:     return '</head>';
 6072: }
 6073: 
 6074: =pod
 6075: 
 6076: =item * &head()
 6077: 
 6078: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6079: 
 6080: Inputs:
 6081: 
 6082: =over 4
 6083: 
 6084: $title - optional title for the page
 6085: 
 6086: $head_extra - optional extra HTML to put inside the <head>
 6087: 
 6088: =back
 6089: 
 6090: =cut
 6091: 
 6092: sub head {
 6093:     my ($title,$head_extra,$args) = @_;
 6094:     return &headtag($title,$head_extra,$args).&endheadtag();
 6095: }
 6096: 
 6097: =pod
 6098: 
 6099: =item * &start_page()
 6100: 
 6101: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6102: 
 6103: Inputs:
 6104: 
 6105: =over 4
 6106: 
 6107: $title - optional title for the page
 6108: 
 6109: $head_extra - optional extra HTML to incude inside the <head>
 6110: 
 6111: $args - additional optional args supported are:
 6112: 
 6113: =over 8
 6114: 
 6115:              only_body      -> is true will set &bodytag() onlybodytag
 6116:                                     arg on
 6117:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6118:              add_entries    -> additional attributes to add to the  <body>
 6119:              domain         -> force to color decorate a page for a 
 6120:                                     specific domain
 6121:              function       -> force usage of a specific rolish color
 6122:                                     scheme
 6123:              redirect       -> see &headtag()
 6124:              bgcolor        -> override the default page bg color
 6125:              js_ready       -> return a string ready for being used in 
 6126:                                     a javascript writeln
 6127:              html_encode    -> return a string ready for being used in 
 6128:                                     a html attribute
 6129:              force_register -> if is true will turn on the &bodytag()
 6130:                                     $forcereg arg
 6131:              body_title     -> alternate text to use instead of $title
 6132:                                     in the title box that appears, this text
 6133:                                     is not auto translated like the $title is
 6134:              frameset       -> if true will start with a <frameset>
 6135:                                     rather than <body>
 6136:              no_title       -> if true the title bar won't be shown
 6137:              skip_phases    -> hash ref of 
 6138:                                     head -> skip the <html><head> generation
 6139:                                     body -> skip all <body> generation
 6140:              no_inline_link -> if true and in remote mode, don't show the 
 6141:                                     'Switch To Inline Menu' link
 6142:              no_auto_mt_title -> prevent &mt()ing the title arg
 6143:              inherit_jsmath -> when creating popup window in a page,
 6144:                                     should it have jsmath forced on by the
 6145:                                     current page
 6146: 
 6147: =back
 6148: 
 6149: =back
 6150: 
 6151: =cut
 6152: 
 6153: sub start_page {
 6154:     my ($title,$head_extra,$args) = @_;
 6155:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6156:     my %head_args;
 6157:     foreach my $arg ('redirect','force_register','domain','function',
 6158: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6159: 		     'no_auto_mt_title') {
 6160: 	if (defined($args->{$arg})) {
 6161: 	    $head_args{$arg} = $args->{$arg};
 6162: 	}
 6163:     }
 6164: 
 6165:     $env{'internal.start_page'}++;
 6166:     my $result;
 6167:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6168: 	$result.=
 6169: 	    &xml_begin().
 6170: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6171:     }
 6172:     
 6173:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6174: 	if ($args->{'frameset'}) {
 6175: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6176: 						$args->{'add_entries'});
 6177: 	    $result .= "\n<frameset $attr_string>\n";
 6178: 	} else {
 6179: 	    $result .=
 6180: 		&bodytag($title, 
 6181: 			 $args->{'function'},       $args->{'add_entries'},
 6182: 			 $args->{'only_body'},      $args->{'domain'},
 6183: 			 $args->{'force_register'}, $args->{'body_title'},
 6184: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6185: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6186: 			 $args);
 6187: 	}
 6188:     }
 6189: 
 6190:     if ($args->{'js_ready'}) {
 6191: 		$result = &js_ready($result);
 6192:     }
 6193:     if ($args->{'html_encode'}) {
 6194: 		$result = &html_encode($result);
 6195:     }
 6196: 
 6197: 	#Breadcrumbs
 6198:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6199: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6200: 		#if any br links exists, add them to the breadcrumbs
 6201: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6202: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6203: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6204: 			}
 6205: 		}
 6206: 
 6207: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6208: 		if(exists($args->{'bread_crumbs_component'})){
 6209: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6210: 		}else{
 6211: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6212: 		}
 6213:     }
 6214:     return $result;
 6215: }
 6216: 
 6217: 
 6218: =pod
 6219: 
 6220: =item * &head()
 6221: 
 6222: Returns a complete </body></html> section for LON-CAPA web pages.
 6223: 
 6224: Inputs:         $args - additional optional args supported are:
 6225:                  js_ready     -> return a string ready for being used in 
 6226:                                  a javascript writeln
 6227:                  html_encode  -> return a string ready for being used in 
 6228:                                  a html attribute
 6229:                  frameset     -> if true will start with a <frameset>
 6230:                                  rather than <body>
 6231:                  dicsussion   -> if true will get discussion from
 6232:                                   lonxml::xmlend
 6233:                                  (you can pass the target and parser arguments
 6234:                                   through optional 'target' and 'parser' args
 6235:                                   to this routine)
 6236: 
 6237: =cut
 6238: 
 6239: sub end_page {
 6240:     my ($args) = @_;
 6241:     $env{'internal.end_page'}++;
 6242:     my $result;
 6243:     if ($args->{'discussion'}) {
 6244: 	my ($target,$parser);
 6245: 	if (ref($args->{'discussion'})) {
 6246: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6247: 				$args->{'discussion'}{'parser'});
 6248: 	}
 6249: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6250:     }
 6251: 
 6252:     if ($args->{'frameset'}) {
 6253: 	$result .= '</frameset>';
 6254:     } else {
 6255: 	$result .= &endbodytag($args);
 6256:     }
 6257:     $result .= "\n</html>";
 6258: 
 6259:     if ($args->{'js_ready'}) {
 6260: 	$result = &js_ready($result);
 6261:     }
 6262: 
 6263:     if ($args->{'html_encode'}) {
 6264: 	$result = &html_encode($result);
 6265:     }
 6266: 
 6267:     return $result;
 6268: }
 6269: 
 6270: sub html_encode {
 6271:     my ($result) = @_;
 6272: 
 6273:     $result = &HTML::Entities::encode($result,'<>&"');
 6274:     
 6275:     return $result;
 6276: }
 6277: sub js_ready {
 6278:     my ($result) = @_;
 6279: 
 6280:     $result =~ s/[\n\r]/ /xmsg;
 6281:     $result =~ s/\\/\\\\/xmsg;
 6282:     $result =~ s/'/\\'/xmsg;
 6283:     $result =~ s{</}{<\\/}xmsg;
 6284:     
 6285:     return $result;
 6286: }
 6287: 
 6288: sub validate_page {
 6289:     if (  exists($env{'internal.start_page'})
 6290: 	  &&     $env{'internal.start_page'} > 1) {
 6291: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6292: 				 $env{'internal.start_page'}.' '.
 6293: 				 $ENV{'request.filename'});
 6294:     }
 6295:     if (  exists($env{'internal.end_page'})
 6296: 	  &&     $env{'internal.end_page'} > 1) {
 6297: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6298: 				 $env{'internal.end_page'}.' '.
 6299: 				 $env{'request.filename'});
 6300:     }
 6301:     if (     exists($env{'internal.start_page'})
 6302: 	&& ! exists($env{'internal.end_page'})) {
 6303: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6304: 				 $env{'request.filename'});
 6305:     }
 6306:     if (   ! exists($env{'internal.start_page'})
 6307: 	&&   exists($env{'internal.end_page'})) {
 6308: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6309: 				 $env{'request.filename'});
 6310:     }
 6311: }
 6312: 
 6313: sub simple_error_page {
 6314:     my ($r,$title,$msg) = @_;
 6315:     my $page =
 6316: 	&Apache::loncommon::start_page($title).
 6317: 	&mt($msg).
 6318: 	&Apache::loncommon::end_page();
 6319:     if (ref($r)) {
 6320: 	$r->print($page);
 6321: 	return;
 6322:     }
 6323:     return $page;
 6324: }
 6325: 
 6326: {
 6327:     my @row_count;
 6328:     sub start_data_table {
 6329: 	my ($add_class) = @_;
 6330: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6331: 	unshift(@row_count,0);
 6332: 	return '<table class="'.$css_class.'">'."\n";
 6333:     }
 6334: 
 6335:     sub end_data_table {
 6336: 	shift(@row_count);
 6337: 	return '</table>'."\n";;
 6338:     }
 6339: 
 6340:     sub start_data_table_row {
 6341: 	my ($add_class) = @_;
 6342: 	$row_count[0]++;
 6343: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6344: 	$css_class = (join(' ',$css_class,$add_class));
 6345: 	return  '<tr class="'.$css_class.'">'."\n";;
 6346:     }
 6347:     
 6348:     sub continue_data_table_row {
 6349: 	my ($add_class) = @_;
 6350: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6351: 	$css_class = (join(' ',$css_class,$add_class));
 6352: 	return  '<tr class="'.$css_class.'">'."\n";;
 6353:     }
 6354: 
 6355:     sub end_data_table_row {
 6356: 	return '</tr>'."\n";;
 6357:     }
 6358: 
 6359:     sub start_data_table_empty_row {
 6360: #	$row_count[0]++;
 6361: 	return  '<tr class="LC_empty_row" >'."\n";;
 6362:     }
 6363: 
 6364:     sub end_data_table_empty_row {
 6365: 	return '</tr>'."\n";;
 6366:     }
 6367: 
 6368:     sub start_data_table_header_row {
 6369: 	return  '<tr class="LC_header_row">'."\n";;
 6370:     }
 6371: 
 6372:     sub end_data_table_header_row {
 6373: 	return '</tr>'."\n";;
 6374:     }
 6375: }
 6376: 
 6377: =pod
 6378: 
 6379: =item * &inhibit_menu_check($arg)
 6380: 
 6381: Checks for a inhibitmenu state and generates output to preserve it
 6382: 
 6383: Inputs:         $arg - can be any of
 6384:                      - undef - in which case the return value is a string 
 6385:                                to add  into arguments list of a uri
 6386:                      - 'input' - in which case the return value is a HTML
 6387:                                  <form> <input> field of type hidden to
 6388:                                  preserve the value
 6389:                      - a url - in which case the return value is the url with
 6390:                                the neccesary cgi args added to preserve the
 6391:                                inhibitmenu state
 6392:                      - a ref to a url - no return value, but the string is
 6393:                                         updated to include the neccessary cgi
 6394:                                         args to preserve the inhibitmenu state
 6395: 
 6396: =cut
 6397: 
 6398: sub inhibit_menu_check {
 6399:     my ($arg) = @_;
 6400:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6401:     if ($arg eq 'input') {
 6402: 	if ($env{'form.inhibitmenu'}) {
 6403: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6404: 	} else {
 6405: 	    return
 6406: 	}
 6407:     }
 6408:     if ($env{'form.inhibitmenu'}) {
 6409: 	if (ref($arg)) {
 6410: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6411: 	} elsif ($arg eq '') {
 6412: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6413: 	} else {
 6414: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6415: 	}
 6416:     }
 6417:     if (!ref($arg)) {
 6418: 	return $arg;
 6419:     }
 6420: }
 6421: 
 6422: ###############################################
 6423: 
 6424: =pod
 6425: 
 6426: =back
 6427: 
 6428: =head1 User Information Routines
 6429: 
 6430: =over 4
 6431: 
 6432: =item * &get_users_function()
 6433: 
 6434: Used by &bodytag to determine the current users primary role.
 6435: Returns either 'student','coordinator','admin', or 'author'.
 6436: 
 6437: =cut
 6438: 
 6439: ###############################################
 6440: sub get_users_function {
 6441:     my $function = 'student';
 6442:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6443:         $function='coordinator';
 6444:     }
 6445:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6446:         $function='admin';
 6447:     }
 6448:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6449:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6450:         $function='author';
 6451:     }
 6452:     return $function;
 6453: }
 6454: 
 6455: ###############################################
 6456: 
 6457: =pod
 6458: 
 6459: =item * &check_user_status()
 6460: 
 6461: Determines current status of supplied role for a
 6462: specific user. Roles can be active, previous or future.
 6463: 
 6464: Inputs: 
 6465: user's domain, user's username, course's domain,
 6466: course's number, optional section ID.
 6467: 
 6468: Outputs:
 6469: role status: active, previous or future. 
 6470: 
 6471: =cut
 6472: 
 6473: sub check_user_status {
 6474:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6475:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6476:     my @uroles = keys %userinfo;
 6477:     my $srchstr;
 6478:     my $active_chk = 'none';
 6479:     my $now = time;
 6480:     if (@uroles > 0) {
 6481:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6482:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6483:         } else {
 6484:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6485:         }
 6486:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6487:             my $role_end = 0;
 6488:             my $role_start = 0;
 6489:             $active_chk = 'active';
 6490:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6491:                 $role_end = $1;
 6492:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6493:                     $role_start = $1;
 6494:                 }
 6495:             }
 6496:             if ($role_start > 0) {
 6497:                 if ($now < $role_start) {
 6498:                     $active_chk = 'future';
 6499:                 }
 6500:             }
 6501:             if ($role_end > 0) {
 6502:                 if ($now > $role_end) {
 6503:                     $active_chk = 'previous';
 6504:                 }
 6505:             }
 6506:         }
 6507:     }
 6508:     return $active_chk;
 6509: }
 6510: 
 6511: ###############################################
 6512: 
 6513: =pod
 6514: 
 6515: =item * &get_sections()
 6516: 
 6517: Determines all the sections for a course including
 6518: sections with students and sections containing other roles.
 6519: Incoming parameters: 
 6520: 
 6521: 1. domain
 6522: 2. course number 
 6523: 3. reference to array containing roles for which sections should 
 6524: be gathered (optional).
 6525: 4. reference to array containing status types for which sections 
 6526: should be gathered (optional).
 6527: 
 6528: If the third argument is undefined, sections are gathered for any role. 
 6529: If the fourth argument is undefined, sections are gathered for any status.
 6530: Permissible values are 'active' or 'future' or 'previous'.
 6531:  
 6532: Returns section hash (keys are section IDs, values are
 6533: number of users in each section), subject to the
 6534: optional roles filter, optional status filter 
 6535: 
 6536: =cut
 6537: 
 6538: ###############################################
 6539: sub get_sections {
 6540:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6541:     if (!defined($cdom) || !defined($cnum)) {
 6542:         my $cid =  $env{'request.course.id'};
 6543: 
 6544: 	return if (!defined($cid));
 6545: 
 6546:         $cdom = $env{'course.'.$cid.'.domain'};
 6547:         $cnum = $env{'course.'.$cid.'.num'};
 6548:     }
 6549: 
 6550:     my %sectioncount;
 6551:     my $now = time;
 6552: 
 6553:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6554: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6555: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6556: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6557:         my $start_index = &Apache::loncoursedata::CL_START();
 6558:         my $end_index = &Apache::loncoursedata::CL_END();
 6559:         my $status;
 6560: 	while (my ($student,$data) = each(%$classlist)) {
 6561: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6562: 				                     $data->[$status_index],
 6563:                                                      $data->[$start_index],
 6564:                                                      $data->[$end_index]);
 6565:             if ($stu_status eq 'Active') {
 6566:                 $status = 'active';
 6567:             } elsif ($end < $now) {
 6568:                 $status = 'previous';
 6569:             } elsif ($start > $now) {
 6570:                 $status = 'future';
 6571:             } 
 6572: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6573:                 if ((!defined($possible_status)) || (($status ne '') && 
 6574:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6575: 		    $sectioncount{$section}++;
 6576:                 }
 6577: 	    }
 6578: 	}
 6579:     }
 6580:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6581:     foreach my $user (sort(keys(%courseroles))) {
 6582: 	if ($user !~ /^(\w{2})/) { next; }
 6583: 	my ($role) = ($user =~ /^(\w{2})/);
 6584: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6585: 	my ($section,$status);
 6586: 	if ($role eq 'cr' &&
 6587: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6588: 	    $section=$1;
 6589: 	}
 6590: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6591: 	if (!defined($section) || $section eq '-1') { next; }
 6592:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6593:         if ($end == -1 && $start == -1) {
 6594:             next; #deleted role
 6595:         }
 6596:         if (!defined($possible_status)) { 
 6597:             $sectioncount{$section}++;
 6598:         } else {
 6599:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6600:                 $status = 'active';
 6601:             } elsif ($end < $now) {
 6602:                 $status = 'future';
 6603:             } elsif ($start > $now) {
 6604:                 $status = 'previous';
 6605:             }
 6606:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6607:                 $sectioncount{$section}++;
 6608:             }
 6609:         }
 6610:     }
 6611:     return %sectioncount;
 6612: }
 6613: 
 6614: ###############################################
 6615: 
 6616: =pod
 6617: 
 6618: =item * &get_course_users()
 6619: 
 6620: Retrieves usernames:domains for users in the specified course
 6621: with specific role(s), and access status. 
 6622: 
 6623: Incoming parameters:
 6624: 1. course domain
 6625: 2. course number
 6626: 3. access status: users must have - either active, 
 6627: previous, future, or all.
 6628: 4. reference to array of permissible roles
 6629: 5. reference to array of section restrictions (optional)
 6630: 6. reference to results object (hash of hashes).
 6631: 7. reference to optional userdata hash
 6632: 8. reference to optional statushash
 6633: 9. flag if privileged users (except those set to unhide in
 6634:    course settings) should be excluded    
 6635: Keys of top level results hash are roles.
 6636: Keys of inner hashes are username:domain, with 
 6637: values set to access type.
 6638: Optional userdata hash returns an array with arguments in the 
 6639: same order as loncoursedata::get_classlist() for student data.
 6640: 
 6641: Optional statushash returns
 6642: 
 6643: Entries for end, start, section and status are blank because
 6644: of the possibility of multiple values for non-student roles.
 6645: 
 6646: =cut
 6647: 
 6648: ###############################################
 6649: 
 6650: sub get_course_users {
 6651:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6652:     my %idx = ();
 6653:     my %seclists;
 6654: 
 6655:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6656:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6657:     $idx{end} = &Apache::loncoursedata::CL_END();
 6658:     $idx{start} = &Apache::loncoursedata::CL_START();
 6659:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6660:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6661:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6662:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6663: 
 6664:     if (grep(/^st$/,@{$roles})) {
 6665:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6666:         my $now = time;
 6667:         foreach my $student (keys(%{$classlist})) {
 6668:             my $match = 0;
 6669:             my $secmatch = 0;
 6670:             my $section = $$classlist{$student}[$idx{section}];
 6671:             my $status = $$classlist{$student}[$idx{status}];
 6672:             if ($section eq '') {
 6673:                 $section = 'none';
 6674:             }
 6675:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6676:                 if (grep(/^all$/,@{$sections})) {
 6677:                     $secmatch = 1;
 6678:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6679:                     if (grep(/^none$/,@{$sections})) {
 6680:                         $secmatch = 1;
 6681:                     }
 6682:                 } else {  
 6683: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6684: 		        $secmatch = 1;
 6685:                     }
 6686: 		}
 6687:                 if (!$secmatch) {
 6688:                     next;
 6689:                 }
 6690:             }
 6691:             if (defined($$types{'active'})) {
 6692:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6693:                     push(@{$$users{st}{$student}},'active');
 6694:                     $match = 1;
 6695:                 }
 6696:             }
 6697:             if (defined($$types{'previous'})) {
 6698:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6699:                     push(@{$$users{st}{$student}},'previous');
 6700:                     $match = 1;
 6701:                 }
 6702:             }
 6703:             if (defined($$types{'future'})) {
 6704:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6705:                     push(@{$$users{st}{$student}},'future');
 6706:                     $match = 1;
 6707:                 }
 6708:             }
 6709:             if ($match) {
 6710:                 push(@{$seclists{$student}},$section);
 6711:                 if (ref($userdata) eq 'HASH') {
 6712:                     $$userdata{$student} = $$classlist{$student};
 6713:                 }
 6714:                 if (ref($statushash) eq 'HASH') {
 6715:                     $statushash->{$student}{'st'}{$section} = $status;
 6716:                 }
 6717:             }
 6718:         }
 6719:     }
 6720:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6721:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6722:         my $now = time;
 6723:         my %displaystatus = ( previous => 'Expired',
 6724:                               active   => 'Active',
 6725:                               future   => 'Future',
 6726:                             );
 6727:         my %nothide;
 6728:         if ($hidepriv) {
 6729:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6730:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6731:                 if ($user !~ /:/) {
 6732:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6733:                 } else {
 6734:                     $nothide{$user} = 1;
 6735:                 }
 6736:             }
 6737:         }
 6738:         foreach my $person (sort(keys(%coursepersonnel))) {
 6739:             my $match = 0;
 6740:             my $secmatch = 0;
 6741:             my $status;
 6742:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6743:             $user =~ s/:$//;
 6744:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6745:             if ($end == -1 || $start == -1) {
 6746:                 next;
 6747:             }
 6748:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6749:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6750:                 my ($uname,$udom) = split(/:/,$user);
 6751:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6752:                     if (grep(/^all$/,@{$sections})) {
 6753:                         $secmatch = 1;
 6754:                     } elsif ($usec eq '') {
 6755:                         if (grep(/^none$/,@{$sections})) {
 6756:                             $secmatch = 1;
 6757:                         }
 6758:                     } else {
 6759:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6760:                             $secmatch = 1;
 6761:                         }
 6762:                     }
 6763:                     if (!$secmatch) {
 6764:                         next;
 6765:                     }
 6766:                 }
 6767:                 if ($usec eq '') {
 6768:                     $usec = 'none';
 6769:                 }
 6770:                 if ($uname ne '' && $udom ne '') {
 6771:                     if ($hidepriv) {
 6772:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6773:                             (!$nothide{$uname.':'.$udom})) {
 6774:                             next;
 6775:                         }
 6776:                     }
 6777:                     if ($end > 0 && $end < $now) {
 6778:                         $status = 'previous';
 6779:                     } elsif ($start > $now) {
 6780:                         $status = 'future';
 6781:                     } else {
 6782:                         $status = 'active';
 6783:                     }
 6784:                     foreach my $type (keys(%{$types})) { 
 6785:                         if ($status eq $type) {
 6786:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6787:                                 push(@{$$users{$role}{$user}},$type);
 6788:                             }
 6789:                             $match = 1;
 6790:                         }
 6791:                     }
 6792:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6793:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6794: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6795:                         }
 6796:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6797:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6798:                         }
 6799:                         if (ref($statushash) eq 'HASH') {
 6800:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6801:                         }
 6802:                     }
 6803:                 }
 6804:             }
 6805:         }
 6806:         if (grep(/^ow$/,@{$roles})) {
 6807:             if ((defined($cdom)) && (defined($cnum))) {
 6808:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6809:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6810:                     my $owner = $csettings{'internal.courseowner'};
 6811:                     next if ($owner eq '');
 6812:                     my ($ownername,$ownerdom);
 6813:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6814:                         $ownername = $1;
 6815:                         $ownerdom = $2;
 6816:                     } else {
 6817:                         $ownername = $owner;
 6818:                         $ownerdom = $cdom;
 6819:                         $owner = $ownername.':'.$ownerdom;
 6820:                     }
 6821:                     @{$$users{'ow'}{$owner}} = 'any';
 6822:                     if (defined($userdata) && 
 6823: 			!exists($$userdata{$owner})) {
 6824: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6825:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6826:                             push(@{$seclists{$owner}},'none');
 6827:                         }
 6828:                         if (ref($statushash) eq 'HASH') {
 6829:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6830:                         }
 6831: 		    }
 6832:                 }
 6833:             }
 6834:         }
 6835:         foreach my $user (keys(%seclists)) {
 6836:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6837:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6838:         }
 6839:     }
 6840:     return;
 6841: }
 6842: 
 6843: sub get_user_info {
 6844:     my ($udom,$uname,$idx,$userdata) = @_;
 6845:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6846: 	&plainname($uname,$udom,'lastname');
 6847:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6848:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6849:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6850:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6851:     return;
 6852: }
 6853: 
 6854: ###############################################
 6855: 
 6856: =pod
 6857: 
 6858: =item * &get_user_quota()
 6859: 
 6860: Retrieves quota assigned for storage of portfolio files for a user  
 6861: 
 6862: Incoming parameters:
 6863: 1. user's username
 6864: 2. user's domain
 6865: 
 6866: Returns:
 6867: 1. Disk quota (in Mb) assigned to student.
 6868: 2. (Optional) Type of setting: custom or default
 6869:    (individually assigned or default for user's 
 6870:    institutional status).
 6871: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6872:    or student - types as defined in localenroll::inst_usertypes 
 6873:    for user's domain, which determines default quota for user.
 6874: 4. (Optional) - Default quota which would apply to the user.
 6875: 
 6876: If a value has been stored in the user's environment, 
 6877: it will return that, otherwise it returns the maximal default
 6878: defined for the user's instituional status(es) in the domain.
 6879: 
 6880: =cut
 6881: 
 6882: ###############################################
 6883: 
 6884: 
 6885: sub get_user_quota {
 6886:     my ($uname,$udom) = @_;
 6887:     my ($quota,$quotatype,$settingstatus,$defquota);
 6888:     if (!defined($udom)) {
 6889:         $udom = $env{'user.domain'};
 6890:     }
 6891:     if (!defined($uname)) {
 6892:         $uname = $env{'user.name'};
 6893:     }
 6894:     if (($udom eq '' || $uname eq '') ||
 6895:         ($udom eq 'public') && ($uname eq 'public')) {
 6896:         $quota = 0;
 6897:         $quotatype = 'default';
 6898:         $defquota = 0; 
 6899:     } else {
 6900:         my $inststatus;
 6901:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6902:             $quota = $env{'environment.portfolioquota'};
 6903:             $inststatus = $env{'environment.inststatus'};
 6904:         } else {
 6905:             my %userenv = 
 6906:                 &Apache::lonnet::get('environment',['portfolioquota',
 6907:                                      'inststatus'],$udom,$uname);
 6908:             my ($tmp) = keys(%userenv);
 6909:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6910:                 $quota = $userenv{'portfolioquota'};
 6911:                 $inststatus = $userenv{'inststatus'};
 6912:             } else {
 6913:                 undef(%userenv);
 6914:             }
 6915:         }
 6916:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6917:         if ($quota eq '') {
 6918:             $quota = $defquota;
 6919:             $quotatype = 'default';
 6920:         } else {
 6921:             $quotatype = 'custom';
 6922:         }
 6923:     }
 6924:     if (wantarray) {
 6925:         return ($quota,$quotatype,$settingstatus,$defquota);
 6926:     } else {
 6927:         return $quota;
 6928:     }
 6929: }
 6930: 
 6931: ###############################################
 6932: 
 6933: =pod
 6934: 
 6935: =item * &default_quota()
 6936: 
 6937: Retrieves default quota assigned for storage of user portfolio files,
 6938: given an (optional) user's institutional status.
 6939: 
 6940: Incoming parameters:
 6941: 1. domain
 6942: 2. (Optional) institutional status(es).  This is a : separated list of 
 6943:    status types (e.g., faculty, staff, student etc.)
 6944:    which apply to the user for whom the default is being retrieved.
 6945:    If the institutional status string in undefined, the domain
 6946:    default quota will be returned. 
 6947: 
 6948: Returns:
 6949: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6950: 2. (Optional) institutional type which determined the value of the
 6951:    default quota.
 6952: 
 6953: If a value has been stored in the domain's configuration db,
 6954: it will return that, otherwise it returns 20 (for backwards 
 6955: compatibility with domains which have not set up a configuration
 6956: db file; the original statically defined portfolio quota was 20 Mb). 
 6957: 
 6958: If the user's status includes multiple types (e.g., staff and student),
 6959: the largest default quota which applies to the user determines the
 6960: default quota returned.
 6961: 
 6962: =cut
 6963: 
 6964: ###############################################
 6965: 
 6966: 
 6967: sub default_quota {
 6968:     my ($udom,$inststatus) = @_;
 6969:     my ($defquota,$settingstatus);
 6970:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6971:                                             ['quotas'],$udom);
 6972:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6973:         if ($inststatus ne '') {
 6974:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 6975:             foreach my $item (@statuses) {
 6976:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6977:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6978:                         if ($defquota eq '') {
 6979:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6980:                             $settingstatus = $item;
 6981:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6982:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6983:                             $settingstatus = $item;
 6984:                         }
 6985:                     }
 6986:                 } else {
 6987:                     if ($quotahash{'quotas'}{$item} ne '') {
 6988:                         if ($defquota eq '') {
 6989:                             $defquota = $quotahash{'quotas'}{$item};
 6990:                             $settingstatus = $item;
 6991:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6992:                             $defquota = $quotahash{'quotas'}{$item};
 6993:                             $settingstatus = $item;
 6994:                         }
 6995:                     }
 6996:                 }
 6997:             }
 6998:         }
 6999:         if ($defquota eq '') {
 7000:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7001:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7002:             } else {
 7003:                 $defquota = $quotahash{'quotas'}{'default'};
 7004:             }
 7005:             $settingstatus = 'default';
 7006:         }
 7007:     } else {
 7008:         $settingstatus = 'default';
 7009:         $defquota = 20;
 7010:     }
 7011:     if (wantarray) {
 7012:         return ($defquota,$settingstatus);
 7013:     } else {
 7014:         return $defquota;
 7015:     }
 7016: }
 7017: 
 7018: sub get_secgrprole_info {
 7019:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7020:     my %sections_count = &get_sections($cdom,$cnum);
 7021:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7022:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7023:     my @groups = sort(keys(%curr_groups));
 7024:     my $allroles = [];
 7025:     my $rolehash;
 7026:     my $accesshash = {
 7027:                      active => 'Currently has access',
 7028:                      future => 'Will have future access',
 7029:                      previous => 'Previously had access',
 7030:                   };
 7031:     if ($needroles) {
 7032:         $rolehash = {'all' => 'all'};
 7033:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7034: 	if (&Apache::lonnet::error(%user_roles)) {
 7035: 	    undef(%user_roles);
 7036: 	}
 7037:         foreach my $item (keys(%user_roles)) {
 7038:             my ($role)=split(/\:/,$item,2);
 7039:             if ($role eq 'cr') { next; }
 7040:             if ($role =~ /^cr/) {
 7041:                 $$rolehash{$role} = (split('/',$role))[3];
 7042:             } else {
 7043:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7044:             }
 7045:         }
 7046:         foreach my $key (sort(keys(%{$rolehash}))) {
 7047:             push(@{$allroles},$key);
 7048:         }
 7049:         push (@{$allroles},'st');
 7050:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7051:     }
 7052:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7053: }
 7054: 
 7055: sub user_picker {
 7056:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7057:     my $currdom = $dom;
 7058:     my %curr_selected = (
 7059:                         srchin => 'dom',
 7060:                         srchby => 'lastname',
 7061:                       );
 7062:     my $srchterm;
 7063:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7064:         if ($srch->{'srchby'} ne '') {
 7065:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7066:         }
 7067:         if ($srch->{'srchin'} ne '') {
 7068:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7069:         }
 7070:         if ($srch->{'srchtype'} ne '') {
 7071:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7072:         }
 7073:         if ($srch->{'srchdomain'} ne '') {
 7074:             $currdom = $srch->{'srchdomain'};
 7075:         }
 7076:         $srchterm = $srch->{'srchterm'};
 7077:     }
 7078:     my %lt=&Apache::lonlocal::texthash(
 7079:                     'usr'       => 'Search criteria',
 7080:                     'doma'      => 'Domain/institution to search',
 7081:                     'uname'     => 'username',
 7082:                     'lastname'  => 'last name',
 7083:                     'lastfirst' => 'last name, first name',
 7084:                     'crs'       => 'in this course',
 7085:                     'dom'       => 'in selected LON-CAPA domain', 
 7086:                     'alc'       => 'all LON-CAPA',
 7087:                     'instd'     => 'in institutional directory for selected domain',
 7088:                     'exact'     => 'is',
 7089:                     'contains'  => 'contains',
 7090:                     'begins'    => 'begins with',
 7091:                     'youm'      => "You must include some text to search for.",
 7092:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7093:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7094:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7095:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7096:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7097:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7098:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7099:                                        );
 7100:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7101:     my $srchinsel = ' <select name="srchin">';
 7102: 
 7103:     my @srchins = ('crs','dom','alc','instd');
 7104: 
 7105:     foreach my $option (@srchins) {
 7106:         # FIXME 'alc' option unavailable until 
 7107:         #       loncreateuser::print_user_query_page()
 7108:         #       has been completed.
 7109:         next if ($option eq 'alc');
 7110:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7111:         if ($curr_selected{'srchin'} eq $option) {
 7112:             $srchinsel .= ' 
 7113:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7114:         } else {
 7115:             $srchinsel .= '
 7116:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7117:         }
 7118:     }
 7119:     $srchinsel .= "\n  </select>\n";
 7120: 
 7121:     my $srchbysel =  ' <select name="srchby">';
 7122:     foreach my $option ('lastname','lastfirst','uname') {
 7123:         if ($curr_selected{'srchby'} eq $option) {
 7124:             $srchbysel .= '
 7125:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7126:         } else {
 7127:             $srchbysel .= '
 7128:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7129:          }
 7130:     }
 7131:     $srchbysel .= "\n  </select>\n";
 7132: 
 7133:     my $srchtypesel = ' <select name="srchtype">';
 7134:     foreach my $option ('begins','contains','exact') {
 7135:         if ($curr_selected{'srchtype'} eq $option) {
 7136:             $srchtypesel .= '
 7137:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7138:         } else {
 7139:             $srchtypesel .= '
 7140:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7141:         }
 7142:     }
 7143:     $srchtypesel .= "\n  </select>\n";
 7144: 
 7145:     my ($newuserscript,$new_user_create);
 7146: 
 7147:     if ($forcenewuser) {
 7148:         if (ref($srch) eq 'HASH') {
 7149:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7150:                 if ($cancreate) {
 7151:                     $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
 7152:                 } else {
 7153:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7154:                     my %usertypetext = (
 7155:                         official   => 'institutional',
 7156:                         unofficial => 'non-institutional',
 7157:                     );
 7158:                     $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
 7159:                 }
 7160:             }
 7161:         }
 7162: 
 7163:         $newuserscript = <<"ENDSCRIPT";
 7164: 
 7165: function setSearch(createnew,callingForm) {
 7166:     if (createnew == 1) {
 7167:         for (var i=0; i<callingForm.srchby.length; i++) {
 7168:             if (callingForm.srchby.options[i].value == 'uname') {
 7169:                 callingForm.srchby.selectedIndex = i;
 7170:             }
 7171:         }
 7172:         for (var i=0; i<callingForm.srchin.length; i++) {
 7173:             if ( callingForm.srchin.options[i].value == 'dom') {
 7174: 		callingForm.srchin.selectedIndex = i;
 7175:             }
 7176:         }
 7177:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7178:             if (callingForm.srchtype.options[i].value == 'exact') {
 7179:                 callingForm.srchtype.selectedIndex = i;
 7180:             }
 7181:         }
 7182:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7183:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7184:                 callingForm.srchdomain.selectedIndex = i;
 7185:             }
 7186:         }
 7187:     }
 7188: }
 7189: ENDSCRIPT
 7190: 
 7191:     }
 7192: 
 7193:     my $output = <<"END_BLOCK";
 7194: <script type="text/javascript">
 7195: function validateEntry(callingForm) {
 7196: 
 7197:     var checkok = 1;
 7198:     var srchin;
 7199:     for (var i=0; i<callingForm.srchin.length; i++) {
 7200: 	if ( callingForm.srchin[i].checked ) {
 7201: 	    srchin = callingForm.srchin[i].value;
 7202: 	}
 7203:     }
 7204: 
 7205:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7206:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7207:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7208:     var srchterm =  callingForm.srchterm.value;
 7209:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7210:     var msg = "";
 7211: 
 7212:     if (srchterm == "") {
 7213:         checkok = 0;
 7214:         msg += "$lt{'youm'}\\n";
 7215:     }
 7216: 
 7217:     if (srchtype== 'begins') {
 7218:         if (srchterm.length < 2) {
 7219:             checkok = 0;
 7220:             msg += "$lt{'thte'}\\n";
 7221:         }
 7222:     }
 7223: 
 7224:     if (srchtype== 'contains') {
 7225:         if (srchterm.length < 3) {
 7226:             checkok = 0;
 7227:             msg += "$lt{'thet'}\\n";
 7228:         }
 7229:     }
 7230:     if (srchin == 'instd') {
 7231:         if (srchdomain == '') {
 7232:             checkok = 0;
 7233:             msg += "$lt{'yomc'}\\n";
 7234:         }
 7235:     }
 7236:     if (srchin == 'dom') {
 7237:         if (srchdomain == '') {
 7238:             checkok = 0;
 7239:             msg += "$lt{'ymcd'}\\n";
 7240:         }
 7241:     }
 7242:     if (srchby == 'lastfirst') {
 7243:         if (srchterm.indexOf(",") == -1) {
 7244:             checkok = 0;
 7245:             msg += "$lt{'whus'}\\n";
 7246:         }
 7247:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7248:             checkok = 0;
 7249:             msg += "$lt{'whse'}\\n";
 7250:         }
 7251:     }
 7252:     if (checkok == 0) {
 7253:         alert("$lt{'thfo'}\\n"+msg);
 7254:         return;
 7255:     }
 7256:     if (checkok == 1) {
 7257:         callingForm.submit();
 7258:     }
 7259: }
 7260: 
 7261: $newuserscript
 7262: 
 7263: </script>
 7264: 
 7265: $new_user_create
 7266: 
 7267: <table>
 7268:  <tr>
 7269:   <td>$lt{'doma'}:</td>
 7270:   <td>$domform</td>
 7271:   </td>
 7272:  </tr>
 7273:  <tr>
 7274:   <td>$lt{'usr'}:</td>
 7275:   <td>$srchbysel
 7276:       $srchtypesel 
 7277:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7278:       $srchinsel 
 7279:   </td>
 7280:  </tr>
 7281: </table>
 7282: <br />
 7283: END_BLOCK
 7284: 
 7285:     return $output;
 7286: }
 7287: 
 7288: sub user_rule_check {
 7289:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7290:     my $response;
 7291:     if (ref($usershash) eq 'HASH') {
 7292:         foreach my $user (keys(%{$usershash})) {
 7293:             my ($uname,$udom) = split(/:/,$user);
 7294:             next if ($udom eq '' || $uname eq '');
 7295:             my ($id,$newuser);
 7296:             if (ref($usershash->{$user}) eq 'HASH') {
 7297:                 $newuser = $usershash->{$user}->{'newuser'};
 7298:                 $id = $usershash->{$user}->{'id'};
 7299:             }
 7300:             my $inst_response;
 7301:             if (ref($checks) eq 'HASH') {
 7302:                 if (defined($checks->{'username'})) {
 7303:                     ($inst_response,%{$inst_results->{$user}}) = 
 7304:                         &Apache::lonnet::get_instuser($udom,$uname);
 7305:                 } elsif (defined($checks->{'id'})) {
 7306:                     ($inst_response,%{$inst_results->{$user}}) =
 7307:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7308:                 }
 7309:             } else {
 7310:                 ($inst_response,%{$inst_results->{$user}}) =
 7311:                     &Apache::lonnet::get_instuser($udom,$uname);
 7312:                 return;
 7313:             }
 7314:             if (!$got_rules->{$udom}) {
 7315:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7316:                                                   ['usercreation'],$udom);
 7317:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7318:                     foreach my $item ('username','id') {
 7319:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7320:                             $$curr_rules{$udom}{$item} = 
 7321:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7322:                         }
 7323:                     }
 7324:                 }
 7325:                 $got_rules->{$udom} = 1;  
 7326:             }
 7327:             foreach my $item (keys(%{$checks})) {
 7328:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7329:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7330:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7331:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7332:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7333:                                 if ($rule_check{$rule}) {
 7334:                                     $$rulematch{$user}{$item} = $rule;
 7335:                                     if ($inst_response eq 'ok') {
 7336:                                         if (ref($inst_results) eq 'HASH') {
 7337:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7338:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7339:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7340:                                                 }
 7341:                                             }
 7342:                                         }
 7343:                                     }
 7344:                                     last;
 7345:                                 }
 7346:                             }
 7347:                         }
 7348:                     }
 7349:                 }
 7350:             }
 7351:         }
 7352:     }
 7353:     return;
 7354: }
 7355: 
 7356: sub user_rule_formats {
 7357:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7358:     my %text = ( 
 7359:                  'username' => 'Usernames',
 7360:                  'id'       => 'IDs',
 7361:                );
 7362:     my $output;
 7363:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7364:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7365:         if (@{$ruleorder} > 0) {
 7366:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
 7367:             foreach my $rule (@{$ruleorder}) {
 7368:                 if (ref($curr_rules) eq 'ARRAY') {
 7369:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7370:                         if (ref($rules->{$rule}) eq 'HASH') {
 7371:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7372:                                         $rules->{$rule}{'desc'}.'</li>';
 7373:                         }
 7374:                     }
 7375:                 }
 7376:             }
 7377:             $output .= '</ul>';
 7378:         }
 7379:     }
 7380:     return $output;
 7381: }
 7382: 
 7383: sub instrule_disallow_msg {
 7384:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7385:     my $response;
 7386:     my %text = (
 7387:                   item   => 'username',
 7388:                   items  => 'usernames',
 7389:                   match  => 'matches',
 7390:                   do     => 'does',
 7391:                   action => 'a username',
 7392:                   one    => 'one',
 7393:                );
 7394:     if ($count > 1) {
 7395:         $text{'item'} = 'usernames';
 7396:         $text{'match'} ='match';
 7397:         $text{'do'} = 'do';
 7398:         $text{'action'} = 'usernames',
 7399:         $text{'one'} = 'ones';
 7400:     }
 7401:     if ($checkitem eq 'id') {
 7402:         $text{'items'} = 'IDs';
 7403:         $text{'item'} = 'ID';
 7404:         $text{'action'} = 'an ID';
 7405:         if ($count > 1) {
 7406:             $text{'item'} = 'IDs';
 7407:             $text{'action'} = 'IDs';
 7408:         }
 7409:     }
 7410:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
 7411:     if ($mode eq 'upload') {
 7412:         if ($checkitem eq 'username') {
 7413:             $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7414:         } elsif ($checkitem eq 'id') {
 7415:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
 7416:         }
 7417:     } elsif ($mode eq 'selfcreate') {
 7418:         if ($checkitem eq 'id') {
 7419:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
 7420:         }
 7421:     } else {
 7422:         if ($checkitem eq 'username') {
 7423:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7424:         } elsif ($checkitem eq 'id') {
 7425:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
 7426:         }
 7427:     }
 7428:     return $response;
 7429: }
 7430: 
 7431: sub personal_data_fieldtitles {
 7432:     my %fieldtitles = &Apache::lonlocal::texthash (
 7433:                         id => 'Student/Employee ID',
 7434:                         permanentemail => 'E-mail address',
 7435:                         lastname => 'Last Name',
 7436:                         firstname => 'First Name',
 7437:                         middlename => 'Middle Name',
 7438:                         generation => 'Generation',
 7439:                         gen => 'Generation',
 7440:                         inststatus => 'Affiliation',
 7441:                    );
 7442:     return %fieldtitles;
 7443: }
 7444: 
 7445: sub sorted_inst_types {
 7446:     my ($dom) = @_;
 7447:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7448:     my $othertitle = &mt('All users');
 7449:     if ($env{'request.course.id'}) {
 7450:         $othertitle  = &mt('Any users');
 7451:     }
 7452:     my @types;
 7453:     if (ref($order) eq 'ARRAY') {
 7454:         @types = @{$order};
 7455:     }
 7456:     if (@types == 0) {
 7457:         if (ref($usertypes) eq 'HASH') {
 7458:             @types = sort(keys(%{$usertypes}));
 7459:         }
 7460:     }
 7461:     if (keys(%{$usertypes}) > 0) {
 7462:         $othertitle = &mt('Other users');
 7463:     }
 7464:     return ($othertitle,$usertypes,\@types);
 7465: }
 7466: 
 7467: sub get_institutional_codes {
 7468:     my ($settings,$allcourses,$LC_code) = @_;
 7469: # Get complete list of course sections to update
 7470:     my @currsections = ();
 7471:     my @currxlists = ();
 7472:     my $coursecode = $$settings{'internal.coursecode'};
 7473: 
 7474:     if ($$settings{'internal.sectionnums'} ne '') {
 7475:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7476:     }
 7477: 
 7478:     if ($$settings{'internal.crosslistings'} ne '') {
 7479:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7480:     }
 7481: 
 7482:     if (@currxlists > 0) {
 7483:         foreach (@currxlists) {
 7484:             if (m/^([^:]+):(\w*)$/) {
 7485:                 unless (grep/^$1$/,@{$allcourses}) {
 7486:                     push @{$allcourses},$1;
 7487:                     $$LC_code{$1} = $2;
 7488:                 }
 7489:             }
 7490:         }
 7491:     }
 7492:  
 7493:     if (@currsections > 0) {
 7494:         foreach (@currsections) {
 7495:             if (m/^(\w+):(\w*)$/) {
 7496:                 my $sec = $coursecode.$1;
 7497:                 my $lc_sec = $2;
 7498:                 unless (grep/^$sec$/,@{$allcourses}) {
 7499:                     push @{$allcourses},$sec;
 7500:                     $$LC_code{$sec} = $lc_sec;
 7501:                 }
 7502:             }
 7503:         }
 7504:     }
 7505:     return;
 7506: }
 7507: 
 7508: =pod
 7509: 
 7510: =back
 7511: 
 7512: =head1 HTTP Helpers
 7513: 
 7514: =over 4
 7515: 
 7516: =item * &get_unprocessed_cgi($query,$possible_names)
 7517: 
 7518: Modify the %env hash to contain unprocessed CGI form parameters held in
 7519: $query.  The parameters listed in $possible_names (an array reference),
 7520: will be set in $env{'form.name'} if they do not already exist.
 7521: 
 7522: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7523: $possible_names is an ref to an array of form element names.  As an example:
 7524: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7525: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7526: 
 7527: =cut
 7528: 
 7529: sub get_unprocessed_cgi {
 7530:   my ($query,$possible_names)= @_;
 7531:   # $Apache::lonxml::debug=1;
 7532:   foreach my $pair (split(/&/,$query)) {
 7533:     my ($name, $value) = split(/=/,$pair);
 7534:     $name = &unescape($name);
 7535:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7536:       $value =~ tr/+/ /;
 7537:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7538:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7539:     }
 7540:   }
 7541: }
 7542: 
 7543: =pod
 7544: 
 7545: =item * &cacheheader() 
 7546: 
 7547: returns cache-controlling header code
 7548: 
 7549: =cut
 7550: 
 7551: sub cacheheader {
 7552:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7553:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7554:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7555:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7556:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7557:     return $output;
 7558: }
 7559: 
 7560: =pod
 7561: 
 7562: =item * &no_cache($r) 
 7563: 
 7564: specifies header code to not have cache
 7565: 
 7566: =cut
 7567: 
 7568: sub no_cache {
 7569:     my ($r) = @_;
 7570:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7571: 	$env{'request.method'} ne 'GET') { return ''; }
 7572:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7573:     $r->no_cache(1);
 7574:     $r->header_out("Expires" => $date);
 7575:     $r->header_out("Pragma" => "no-cache");
 7576: }
 7577: 
 7578: sub content_type {
 7579:     my ($r,$type,$charset) = @_;
 7580:     if ($r) {
 7581: 	#  Note that printout.pl calls this with undef for $r.
 7582: 	&no_cache($r);
 7583:     }
 7584:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7585:     unless ($charset) {
 7586: 	$charset=&Apache::lonlocal::current_encoding;
 7587:     }
 7588:     if ($charset) { $type.='; charset='.$charset; }
 7589:     if ($r) {
 7590: 	$r->content_type($type);
 7591:     } else {
 7592: 	print("Content-type: $type\n\n");
 7593:     }
 7594: }
 7595: 
 7596: =pod
 7597: 
 7598: =item * &add_to_env($name,$value) 
 7599: 
 7600: adds $name to the %env hash with value
 7601: $value, if $name already exists, the entry is converted to an array
 7602: reference and $value is added to the array.
 7603: 
 7604: =cut
 7605: 
 7606: sub add_to_env {
 7607:   my ($name,$value)=@_;
 7608:   if (defined($env{$name})) {
 7609:     if (ref($env{$name})) {
 7610:       #already have multiple values
 7611:       push(@{ $env{$name} },$value);
 7612:     } else {
 7613:       #first time seeing multiple values, convert hash entry to an arrayref
 7614:       my $first=$env{$name};
 7615:       undef($env{$name});
 7616:       push(@{ $env{$name} },$first,$value);
 7617:     }
 7618:   } else {
 7619:     $env{$name}=$value;
 7620:   }
 7621: }
 7622: 
 7623: =pod
 7624: 
 7625: =item * &get_env_multiple($name) 
 7626: 
 7627: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7628: values may be defined and end up as an array ref.
 7629: 
 7630: returns an array of values
 7631: 
 7632: =cut
 7633: 
 7634: sub get_env_multiple {
 7635:     my ($name) = @_;
 7636:     my @values;
 7637:     if (defined($env{$name})) {
 7638:         # exists is it an array
 7639:         if (ref($env{$name})) {
 7640:             @values=@{ $env{$name} };
 7641:         } else {
 7642:             $values[0]=$env{$name};
 7643:         }
 7644:     }
 7645:     return(@values);
 7646: }
 7647: 
 7648: sub ask_for_embedded_content {
 7649:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7650:     my $upload_output = '
 7651:    <form name="upload_embedded" action="'.$actionurl.'"
 7652:                   method="post" enctype="multipart/form-data">';
 7653:     $upload_output .= $state;
 7654:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7655: 
 7656:     my $num = 0;
 7657:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7658:         $upload_output .= &start_data_table_row().
 7659:             '<td>'.$embed_file.'</td><td>';
 7660:         if ($args->{'ignore_remote_references'}
 7661:             && $embed_file =~ m{^\w+://}) {
 7662:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7663:         } elsif ($args->{'error_on_invalid_names'}
 7664:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7665: 
 7666:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7667: 
 7668:         } else {
 7669:             $upload_output .='
 7670:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7671:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7672:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7673:             $upload_output .=
 7674:                 "\n\t\t".
 7675:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7676:                 $attrib.'" />';
 7677:             if (exists($$codebase{$embed_file})) {
 7678:                 $upload_output .=
 7679:                     "\n\t\t".
 7680:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7681:                     &escape($$codebase{$embed_file}).'" />';
 7682:             }
 7683:         }
 7684:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7685:         $num++;
 7686:     }
 7687:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7688:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7689:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7690:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7691:    </form>';
 7692:     return $upload_output;
 7693: }
 7694: 
 7695: sub upload_embedded {
 7696:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7697:         $current_disk_usage) = @_;
 7698:     my $output;
 7699:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7700:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7701:         my $orig_uploaded_filename =
 7702:             $env{'form.embedded_item_'.$i.'.filename'};
 7703: 
 7704:         $env{'form.embedded_orig_'.$i} =
 7705:             &unescape($env{'form.embedded_orig_'.$i});
 7706:         my ($path,$fname) =
 7707:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7708:         # no path, whole string is fname
 7709:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7710: 
 7711:         $path = $env{'form.currentpath'}.$path;
 7712:         $fname = &Apache::lonnet::clean_filename($fname);
 7713:         # See if there is anything left
 7714:         next if ($fname eq '');
 7715: 
 7716:         # Check if file already exists as a file or directory.
 7717:         my ($state,$msg);
 7718:         if ($context eq 'portfolio') {
 7719:             my $port_path = $dirpath;
 7720:             if ($group ne '') {
 7721:                 $port_path = "groups/$group/$port_path";
 7722:             }
 7723:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7724:                                               $dir_root,$port_path,$disk_quota,
 7725:                                               $current_disk_usage,$uname,$udom);
 7726:             if ($state eq 'will_exceed_quota'
 7727:                 || $state eq 'file_locked'
 7728:                 || $state eq 'file_exists' ) {
 7729:                 $output .= $msg;
 7730:                 next;
 7731:             }
 7732:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7733:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7734:             if ($state eq 'exists') {
 7735:                 $output .= $msg;
 7736:                 next;
 7737:             }
 7738:         }
 7739:         # Check if extension is valid
 7740:         if (($fname =~ /\.(\w+)$/) &&
 7741:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7742:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7743:             next;
 7744:         } elsif (($fname =~ /\.(\w+)$/) &&
 7745:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7746:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7747:             next;
 7748:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7749:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7750:             next;
 7751:         }
 7752: 
 7753:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7754:         if ($context eq 'portfolio') {
 7755:             my $result=
 7756:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7757:                                                 $dirpath.$path);
 7758:             if ($result !~ m|^/uploaded/|) {
 7759:                 $output .= '<span class="LC_error">'
 7760:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7761:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7762:                       .'</span><br />';
 7763:                 next;
 7764:             } else {
 7765:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7766:                            $path.$fname.'</span>').'</p>';     
 7767:             }
 7768:         } else {
 7769: # Save the file
 7770:             my $target = $env{'form.embedded_item_'.$i};
 7771:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7772:             my $dest = $fullpath.$fname;
 7773:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7774:             my @parts=split(/\//,$fullpath);
 7775:             my $count;
 7776:             my $filepath = $dir_root;
 7777:             for ($count=4;$count<=$#parts;$count++) {
 7778:                 $filepath .= "/$parts[$count]";
 7779:                 if ((-e $filepath)!=1) {
 7780:                     mkdir($filepath,0770);
 7781:                 }
 7782:             }
 7783:             my $fh;
 7784:             if (!open($fh,'>'.$dest)) {
 7785:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7786:                 $output .= '<span class="LC_error">'.
 7787:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7788:                            '</span><br />';
 7789:             } else {
 7790:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7791:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7792:                     $output .= '<span class="LC_error">'.
 7793:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7794:                               '</span><br />';
 7795:                 } else {
 7796:                     if ($context eq 'testbank') {
 7797:                         $output .= &mt('Embedded file uploaded successfully:').
 7798:                                    '&nbsp;<a href="'.$url.'">'.
 7799:                                    $orig_uploaded_filename.'</a><br />';
 7800:                     } else {
 7801:                         $output .= '<span class=\"LC_fontsize_large\">'.
 7802:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7803:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 7804:                     }
 7805:                 }
 7806:                 close($fh);
 7807:             }
 7808:         }
 7809:     }
 7810:     return $output;
 7811: }
 7812: 
 7813: sub check_for_existing {
 7814:     my ($path,$fname,$element) = @_;
 7815:     my ($state,$msg);
 7816:     if (-d $path.'/'.$fname) {
 7817:         $state = 'exists';
 7818:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7819:     } elsif (-e $path.'/'.$fname) {
 7820:         $state = 'exists';
 7821:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7822:     }
 7823:     if ($state eq 'exists') {
 7824:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7825:     }
 7826:     return ($state,$msg);
 7827: }
 7828: 
 7829: sub check_for_upload {
 7830:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7831:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7832:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7833:     my $getpropath = 1;
 7834:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7835:                                             $getpropath);
 7836:     my $found_file = 0;
 7837:     my $locked_file = 0;
 7838:     foreach my $line (@dir_list) {
 7839:         my ($file_name)=split(/\&/,$line,2);
 7840:         if ($file_name eq $fname){
 7841:             $file_name = $path.$file_name;
 7842:             if ($group ne '') {
 7843:                 $file_name = $group.$file_name;
 7844:             }
 7845:             $found_file = 1;
 7846:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7847:                 $locked_file = 1;
 7848:             }
 7849:         }
 7850:     }
 7851:     if (($current_disk_usage + $filesize) > $disk_quota){
 7852:         my $msg = '<span class="LC_error">'.
 7853:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7854:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7855:         return ('will_exceed_quota',$msg);
 7856:     } elsif ($found_file) {
 7857:         if ($locked_file) {
 7858:             my $msg = '<span class="LC_error">';
 7859:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
 7860:             $msg .= '</span><br />';
 7861:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7862:             return ('file_locked',$msg);
 7863:         } else {
 7864:             my $msg = '<span class="LC_error">';
 7865:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 7866:             $msg .= '</span>';
 7867:             $msg .= '<br />';
 7868:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7869:             return ('file_exists',$msg);
 7870:         }
 7871:     }
 7872: }
 7873: 
 7874: 
 7875: =pod
 7876: 
 7877: =back
 7878: 
 7879: =head1 CSV Upload/Handling functions
 7880: 
 7881: =over 4
 7882: 
 7883: =item * &upfile_store($r)
 7884: 
 7885: Store uploaded file, $r should be the HTTP Request object,
 7886: needs $env{'form.upfile'}
 7887: returns $datatoken to be put into hidden field
 7888: 
 7889: =cut
 7890: 
 7891: sub upfile_store {
 7892:     my $r=shift;
 7893:     $env{'form.upfile'}=~s/\r/\n/gs;
 7894:     $env{'form.upfile'}=~s/\f/\n/gs;
 7895:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7896:     $env{'form.upfile'}=~s/\n+$//gs;
 7897: 
 7898:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7899: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7900:     {
 7901:         my $datafile = $r->dir_config('lonDaemons').
 7902:                            '/tmp/'.$datatoken.'.tmp';
 7903:         if ( open(my $fh,">$datafile") ) {
 7904:             print $fh $env{'form.upfile'};
 7905:             close($fh);
 7906:         }
 7907:     }
 7908:     return $datatoken;
 7909: }
 7910: 
 7911: =pod
 7912: 
 7913: =item * &load_tmp_file($r)
 7914: 
 7915: Load uploaded file from tmp, $r should be the HTTP Request object,
 7916: needs $env{'form.datatoken'},
 7917: sets $env{'form.upfile'} to the contents of the file
 7918: 
 7919: =cut
 7920: 
 7921: sub load_tmp_file {
 7922:     my $r=shift;
 7923:     my @studentdata=();
 7924:     {
 7925:         my $studentfile = $r->dir_config('lonDaemons').
 7926:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7927:         if ( open(my $fh,"<$studentfile") ) {
 7928:             @studentdata=<$fh>;
 7929:             close($fh);
 7930:         }
 7931:     }
 7932:     $env{'form.upfile'}=join('',@studentdata);
 7933: }
 7934: 
 7935: =pod
 7936: 
 7937: =item * &upfile_record_sep()
 7938: 
 7939: Separate uploaded file into records
 7940: returns array of records,
 7941: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7942: 
 7943: =cut
 7944: 
 7945: sub upfile_record_sep {
 7946:     if ($env{'form.upfiletype'} eq 'xml') {
 7947:     } else {
 7948: 	my @records;
 7949: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7950: 	    if ($line=~/^\s*$/) { next; }
 7951: 	    push(@records,$line);
 7952: 	}
 7953: 	return @records;
 7954:     }
 7955: }
 7956: 
 7957: =pod
 7958: 
 7959: =item * &record_sep($record)
 7960: 
 7961: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7962: 
 7963: =cut
 7964: 
 7965: sub takeleft {
 7966:     my $index=shift;
 7967:     return substr('0000'.$index,-4,4);
 7968: }
 7969: 
 7970: sub record_sep {
 7971:     my $record=shift;
 7972:     my %components=();
 7973:     if ($env{'form.upfiletype'} eq 'xml') {
 7974:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7975:         my $i=0;
 7976:         foreach my $field (split(/\s+/,$record)) {
 7977:             $field=~s/^(\"|\')//;
 7978:             $field=~s/(\"|\')$//;
 7979:             $components{&takeleft($i)}=$field;
 7980:             $i++;
 7981:         }
 7982:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7983:         my $i=0;
 7984:         foreach my $field (split(/\t/,$record)) {
 7985:             $field=~s/^(\"|\')//;
 7986:             $field=~s/(\"|\')$//;
 7987:             $components{&takeleft($i)}=$field;
 7988:             $i++;
 7989:         }
 7990:     } else {
 7991:         my $separator=',';
 7992:         if ($env{'form.upfiletype'} eq 'semisv') {
 7993:             $separator=';';
 7994:         }
 7995:         my $i=0;
 7996: # the character we are looking for to indicate the end of a quote or a record 
 7997:         my $looking_for=$separator;
 7998: # do not add the characters to the fields
 7999:         my $ignore=0;
 8000: # we just encountered a separator (or the beginning of the record)
 8001:         my $just_found_separator=1;
 8002: # store the field we are working on here
 8003:         my $field='';
 8004: # work our way through all characters in record
 8005:         foreach my $character ($record=~/(.)/g) {
 8006:             if ($character eq $looking_for) {
 8007:                if ($character ne $separator) {
 8008: # Found the end of a quote, again looking for separator
 8009:                   $looking_for=$separator;
 8010:                   $ignore=1;
 8011:                } else {
 8012: # Found a separator, store away what we got
 8013:                   $components{&takeleft($i)}=$field;
 8014: 	          $i++;
 8015:                   $just_found_separator=1;
 8016:                   $ignore=0;
 8017:                   $field='';
 8018:                }
 8019:                next;
 8020:             }
 8021: # single or double quotation marks after a separator indicate beginning of a quote
 8022: # we are now looking for the end of the quote and need to ignore separators
 8023:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8024:                $looking_for=$character;
 8025:                next;
 8026:             }
 8027: # ignore would be true after we reached the end of a quote
 8028:             if ($ignore) { next; }
 8029:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8030:             $field.=$character;
 8031:             $just_found_separator=0; 
 8032:         }
 8033: # catch the very last entry, since we never encountered the separator
 8034:         $components{&takeleft($i)}=$field;
 8035:     }
 8036:     return %components;
 8037: }
 8038: 
 8039: ######################################################
 8040: ######################################################
 8041: 
 8042: =pod
 8043: 
 8044: =item * &upfile_select_html()
 8045: 
 8046: Return HTML code to select a file from the users machine and specify 
 8047: the file type.
 8048: 
 8049: =cut
 8050: 
 8051: ######################################################
 8052: ######################################################
 8053: sub upfile_select_html {
 8054:     my %Types = (
 8055:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8056:                  semisv => &mt('Semicolon separated values'),
 8057:                  space => &mt('Space separated'),
 8058:                  tab   => &mt('Tabulator separated'),
 8059: #                 xml   => &mt('HTML/XML'),
 8060:                  );
 8061:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8062:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8063:     foreach my $type (sort(keys(%Types))) {
 8064:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8065:     }
 8066:     $Str .= "</select>\n";
 8067:     return $Str;
 8068: }
 8069: 
 8070: sub get_samples {
 8071:     my ($records,$toget) = @_;
 8072:     my @samples=({});
 8073:     my $got=0;
 8074:     foreach my $rec (@$records) {
 8075: 	my %temp = &record_sep($rec);
 8076: 	if (! grep(/\S/, values(%temp))) { next; }
 8077: 	if (%temp) {
 8078: 	    $samples[$got]=\%temp;
 8079: 	    $got++;
 8080: 	    if ($got == $toget) { last; }
 8081: 	}
 8082:     }
 8083:     return \@samples;
 8084: }
 8085: 
 8086: ######################################################
 8087: ######################################################
 8088: 
 8089: =pod
 8090: 
 8091: =item * &csv_print_samples($r,$records)
 8092: 
 8093: Prints a table of sample values from each column uploaded $r is an
 8094: Apache Request ref, $records is an arrayref from
 8095: &Apache::loncommon::upfile_record_sep
 8096: 
 8097: =cut
 8098: 
 8099: ######################################################
 8100: ######################################################
 8101: sub csv_print_samples {
 8102:     my ($r,$records) = @_;
 8103:     my $samples = &get_samples($records,5);
 8104: 
 8105:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8106:               &start_data_table_header_row());
 8107:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8108:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8109:     $r->print(&end_data_table_header_row());
 8110:     foreach my $hash (@$samples) {
 8111: 	$r->print(&start_data_table_row());
 8112: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8113: 	    $r->print('<td>');
 8114: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8115: 	    $r->print('</td>');
 8116: 	}
 8117: 	$r->print(&end_data_table_row());
 8118:     }
 8119:     $r->print(&end_data_table().'<br />'."\n");
 8120: }
 8121: 
 8122: ######################################################
 8123: ######################################################
 8124: 
 8125: =pod
 8126: 
 8127: =item * &csv_print_select_table($r,$records,$d)
 8128: 
 8129: Prints a table to create associations between values and table columns.
 8130: 
 8131: $r is an Apache Request ref,
 8132: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8133: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8134: 
 8135: =cut
 8136: 
 8137: ######################################################
 8138: ######################################################
 8139: sub csv_print_select_table {
 8140:     my ($r,$records,$d) = @_;
 8141:     my $i=0;
 8142:     my $samples = &get_samples($records,1);
 8143:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8144: 	      &start_data_table().&start_data_table_header_row().
 8145:               '<th>'.&mt('Attribute').'</th>'.
 8146:               '<th>'.&mt('Column').'</th>'.
 8147:               &end_data_table_header_row()."\n");
 8148:     foreach my $array_ref (@$d) {
 8149: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8150: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8151: 
 8152: 	$r->print('<td><select name=f'.$i.
 8153: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8154: 	$r->print('<option value="none"></option>');
 8155: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8156: 	    $r->print('<option value="'.$sample.'"'.
 8157:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8158:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8159: 	}
 8160: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8161: 	$i++;
 8162:     }
 8163:     $r->print(&end_data_table());
 8164:     $i--;
 8165:     return $i;
 8166: }
 8167: 
 8168: ######################################################
 8169: ######################################################
 8170: 
 8171: =pod
 8172: 
 8173: =item * &csv_samples_select_table($r,$records,$d)
 8174: 
 8175: Prints a table of sample values from the upload and can make associate samples to internal names.
 8176: 
 8177: $r is an Apache Request ref,
 8178: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8179: $d is an array of 2 element arrays (internal name, displayed name)
 8180: 
 8181: =cut
 8182: 
 8183: ######################################################
 8184: ######################################################
 8185: sub csv_samples_select_table {
 8186:     my ($r,$records,$d) = @_;
 8187:     my $i=0;
 8188:     #
 8189:     my $max_samples = 5;
 8190:     my $samples = &get_samples($records,$max_samples);
 8191:     $r->print(&start_data_table().
 8192:               &start_data_table_header_row().'<th>'.
 8193:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8194:               &end_data_table_header_row());
 8195: 
 8196:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8197: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8198: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8199: 	foreach my $option (@$d) {
 8200: 	    my ($value,$display,$defaultcol)=@{ $option };
 8201: 	    $r->print('<option value="'.$value.'"'.
 8202:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8203:                       $display.'</option>');
 8204: 	}
 8205: 	$r->print('</select></td><td>');
 8206: 	foreach my $line (0..($max_samples-1)) {
 8207: 	    if (defined($samples->[$line]{$key})) { 
 8208: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8209: 	    }
 8210: 	}
 8211: 	$r->print('</td>'.&end_data_table_row());
 8212: 	$i++;
 8213:     }
 8214:     $r->print(&end_data_table());
 8215:     $i--;
 8216:     return($i);
 8217: }
 8218: 
 8219: ######################################################
 8220: ######################################################
 8221: 
 8222: =pod
 8223: 
 8224: =item * &clean_excel_name($name)
 8225: 
 8226: Returns a replacement for $name which does not contain any illegal characters.
 8227: 
 8228: =cut
 8229: 
 8230: ######################################################
 8231: ######################################################
 8232: sub clean_excel_name {
 8233:     my ($name) = @_;
 8234:     $name =~ s/[:\*\?\/\\]//g;
 8235:     if (length($name) > 31) {
 8236:         $name = substr($name,0,31);
 8237:     }
 8238:     return $name;
 8239: }
 8240: 
 8241: =pod
 8242: 
 8243: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8244: 
 8245: Returns either 1 or undef
 8246: 
 8247: 1 if the part is to be hidden, undef if it is to be shown
 8248: 
 8249: Arguments are:
 8250: 
 8251: $id the id of the part to be checked
 8252: $symb, optional the symb of the resource to check
 8253: $udom, optional the domain of the user to check for
 8254: $uname, optional the username of the user to check for
 8255: 
 8256: =cut
 8257: 
 8258: sub check_if_partid_hidden {
 8259:     my ($id,$symb,$udom,$uname) = @_;
 8260:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8261: 					 $symb,$udom,$uname);
 8262:     my $truth=1;
 8263:     #if the string starts with !, then the list is the list to show not hide
 8264:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8265:     my @hiddenlist=split(/,/,$hiddenparts);
 8266:     foreach my $checkid (@hiddenlist) {
 8267: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8268:     }
 8269:     return !$truth;
 8270: }
 8271: 
 8272: 
 8273: ############################################################
 8274: ############################################################
 8275: 
 8276: =pod
 8277: 
 8278: =back 
 8279: 
 8280: =head1 cgi-bin script and graphing routines
 8281: 
 8282: =over 4
 8283: 
 8284: =item * &get_cgi_id()
 8285: 
 8286: Inputs: none
 8287: 
 8288: Returns an id which can be used to pass environment variables
 8289: to various cgi-bin scripts.  These environment variables will
 8290: be removed from the users environment after a given time by
 8291: the routine &Apache::lonnet::transfer_profile_to_env.
 8292: 
 8293: =cut
 8294: 
 8295: ############################################################
 8296: ############################################################
 8297: my $uniq=0;
 8298: sub get_cgi_id {
 8299:     $uniq=($uniq+1)%100000;
 8300:     return (time.'_'.$$.'_'.$uniq);
 8301: }
 8302: 
 8303: ############################################################
 8304: ############################################################
 8305: 
 8306: =pod
 8307: 
 8308: =item * &DrawBarGraph()
 8309: 
 8310: Facilitates the plotting of data in a (stacked) bar graph.
 8311: Puts plot definition data into the users environment in order for 
 8312: graph.png to plot it.  Returns an <img> tag for the plot.
 8313: The bars on the plot are labeled '1','2',...,'n'.
 8314: 
 8315: Inputs:
 8316: 
 8317: =over 4
 8318: 
 8319: =item $Title: string, the title of the plot
 8320: 
 8321: =item $xlabel: string, text describing the X-axis of the plot
 8322: 
 8323: =item $ylabel: string, text describing the Y-axis of the plot
 8324: 
 8325: =item $Max: scalar, the maximum Y value to use in the plot
 8326: If $Max is < any data point, the graph will not be rendered.
 8327: 
 8328: =item $colors: array ref holding the colors to be used for the data sets when
 8329: they are plotted.  If undefined, default values will be used.
 8330: 
 8331: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8332: 
 8333: =item @Values: An array of array references.  Each array reference holds data
 8334: to be plotted in a stacked bar chart.
 8335: 
 8336: =item If the final element of @Values is a hash reference the key/value
 8337: pairs will be added to the graph definition.
 8338: 
 8339: =back
 8340: 
 8341: Returns:
 8342: 
 8343: An <img> tag which references graph.png and the appropriate identifying
 8344: information for the plot.
 8345: 
 8346: =cut
 8347: 
 8348: ############################################################
 8349: ############################################################
 8350: sub DrawBarGraph {
 8351:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8352:     #
 8353:     if (! defined($colors)) {
 8354:         $colors = ['#33ff00', 
 8355:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8356:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8357:                   ]; 
 8358:     }
 8359:     my $extra_settings = {};
 8360:     if (ref($Values[-1]) eq 'HASH') {
 8361:         $extra_settings = pop(@Values);
 8362:     }
 8363:     #
 8364:     my $identifier = &get_cgi_id();
 8365:     my $id = 'cgi.'.$identifier;        
 8366:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8367:         return '';
 8368:     }
 8369:     #
 8370:     my @Labels;
 8371:     if (defined($labels)) {
 8372:         @Labels = @$labels;
 8373:     } else {
 8374:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8375:             push (@Labels,$i+1);
 8376:         }
 8377:     }
 8378:     #
 8379:     my $NumBars = scalar(@{$Values[0]});
 8380:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8381:     my %ValuesHash;
 8382:     my $NumSets=1;
 8383:     foreach my $array (@Values) {
 8384:         next if (! ref($array));
 8385:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8386:             join(',',@$array);
 8387:     }
 8388:     #
 8389:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8390:     if ($NumBars < 3) {
 8391:         $width = 120+$NumBars*32;
 8392:         $xskip = 1;
 8393:         $bar_width = 30;
 8394:     } elsif ($NumBars < 5) {
 8395:         $width = 120+$NumBars*20;
 8396:         $xskip = 1;
 8397:         $bar_width = 20;
 8398:     } elsif ($NumBars < 10) {
 8399:         $width = 120+$NumBars*15;
 8400:         $xskip = 1;
 8401:         $bar_width = 15;
 8402:     } elsif ($NumBars <= 25) {
 8403:         $width = 120+$NumBars*11;
 8404:         $xskip = 5;
 8405:         $bar_width = 8;
 8406:     } elsif ($NumBars <= 50) {
 8407:         $width = 120+$NumBars*8;
 8408:         $xskip = 5;
 8409:         $bar_width = 4;
 8410:     } else {
 8411:         $width = 120+$NumBars*8;
 8412:         $xskip = 5;
 8413:         $bar_width = 4;
 8414:     }
 8415:     #
 8416:     $Max = 1 if ($Max < 1);
 8417:     if ( int($Max) < $Max ) {
 8418:         $Max++;
 8419:         $Max = int($Max);
 8420:     }
 8421:     $Title  = '' if (! defined($Title));
 8422:     $xlabel = '' if (! defined($xlabel));
 8423:     $ylabel = '' if (! defined($ylabel));
 8424:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8425:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8426:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8427:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8428:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8429:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8430:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8431:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8432:     $ValuesHash{$id.'.height'}   = $height;
 8433:     $ValuesHash{$id.'.width'}    = $width;
 8434:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8435:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8436:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8437:     #
 8438:     # Deal with other parameters
 8439:     while (my ($key,$value) = each(%$extra_settings)) {
 8440:         $ValuesHash{$id.'.'.$key} = $value;
 8441:     }
 8442:     #
 8443:     &Apache::lonnet::appenv(\%ValuesHash);
 8444:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8445: }
 8446: 
 8447: ############################################################
 8448: ############################################################
 8449: 
 8450: =pod
 8451: 
 8452: =item * &DrawXYGraph()
 8453: 
 8454: Facilitates the plotting of data in an XY graph.
 8455: Puts plot definition data into the users environment in order for 
 8456: graph.png to plot it.  Returns an <img> tag for the plot.
 8457: 
 8458: Inputs:
 8459: 
 8460: =over 4
 8461: 
 8462: =item $Title: string, the title of the plot
 8463: 
 8464: =item $xlabel: string, text describing the X-axis of the plot
 8465: 
 8466: =item $ylabel: string, text describing the Y-axis of the plot
 8467: 
 8468: =item $Max: scalar, the maximum Y value to use in the plot
 8469: If $Max is < any data point, the graph will not be rendered.
 8470: 
 8471: =item $colors: Array ref containing the hex color codes for the data to be 
 8472: plotted in.  If undefined, default values will be used.
 8473: 
 8474: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8475: 
 8476: =item $Ydata: Array ref containing Array refs.  
 8477: Each of the contained arrays will be plotted as a separate curve.
 8478: 
 8479: =item %Values: hash indicating or overriding any default values which are 
 8480: passed to graph.png.  
 8481: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8482: 
 8483: =back
 8484: 
 8485: Returns:
 8486: 
 8487: An <img> tag which references graph.png and the appropriate identifying
 8488: information for the plot.
 8489: 
 8490: =cut
 8491: 
 8492: ############################################################
 8493: ############################################################
 8494: sub DrawXYGraph {
 8495:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8496:     #
 8497:     # Create the identifier for the graph
 8498:     my $identifier = &get_cgi_id();
 8499:     my $id = 'cgi.'.$identifier;
 8500:     #
 8501:     $Title  = '' if (! defined($Title));
 8502:     $xlabel = '' if (! defined($xlabel));
 8503:     $ylabel = '' if (! defined($ylabel));
 8504:     my %ValuesHash = 
 8505:         (
 8506:          $id.'.title'  => &escape($Title),
 8507:          $id.'.xlabel' => &escape($xlabel),
 8508:          $id.'.ylabel' => &escape($ylabel),
 8509:          $id.'.y_max_value'=> $Max,
 8510:          $id.'.labels'     => join(',',@$Xlabels),
 8511:          $id.'.PlotType'   => 'XY',
 8512:          );
 8513:     #
 8514:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8515:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8516:     }
 8517:     #
 8518:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8519:         return '';
 8520:     }
 8521:     my $NumSets=1;
 8522:     foreach my $array (@{$Ydata}){
 8523:         next if (! ref($array));
 8524:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8525:     }
 8526:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8527:     #
 8528:     # Deal with other parameters
 8529:     while (my ($key,$value) = each(%Values)) {
 8530:         $ValuesHash{$id.'.'.$key} = $value;
 8531:     }
 8532:     #
 8533:     &Apache::lonnet::appenv(\%ValuesHash);
 8534:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8535: }
 8536: 
 8537: ############################################################
 8538: ############################################################
 8539: 
 8540: =pod
 8541: 
 8542: =item * &DrawXYYGraph()
 8543: 
 8544: Facilitates the plotting of data in an XY graph with two Y axes.
 8545: Puts plot definition data into the users environment in order for 
 8546: graph.png to plot it.  Returns an <img> tag for the plot.
 8547: 
 8548: Inputs:
 8549: 
 8550: =over 4
 8551: 
 8552: =item $Title: string, the title of the plot
 8553: 
 8554: =item $xlabel: string, text describing the X-axis of the plot
 8555: 
 8556: =item $ylabel: string, text describing the Y-axis of the plot
 8557: 
 8558: =item $colors: Array ref containing the hex color codes for the data to be 
 8559: plotted in.  If undefined, default values will be used.
 8560: 
 8561: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8562: 
 8563: =item $Ydata1: The first data set
 8564: 
 8565: =item $Min1: The minimum value of the left Y-axis
 8566: 
 8567: =item $Max1: The maximum value of the left Y-axis
 8568: 
 8569: =item $Ydata2: The second data set
 8570: 
 8571: =item $Min2: The minimum value of the right Y-axis
 8572: 
 8573: =item $Max2: The maximum value of the left Y-axis
 8574: 
 8575: =item %Values: hash indicating or overriding any default values which are 
 8576: passed to graph.png.  
 8577: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8578: 
 8579: =back
 8580: 
 8581: Returns:
 8582: 
 8583: An <img> tag which references graph.png and the appropriate identifying
 8584: information for the plot.
 8585: 
 8586: =cut
 8587: 
 8588: ############################################################
 8589: ############################################################
 8590: sub DrawXYYGraph {
 8591:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8592:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8593:     #
 8594:     # Create the identifier for the graph
 8595:     my $identifier = &get_cgi_id();
 8596:     my $id = 'cgi.'.$identifier;
 8597:     #
 8598:     $Title  = '' if (! defined($Title));
 8599:     $xlabel = '' if (! defined($xlabel));
 8600:     $ylabel = '' if (! defined($ylabel));
 8601:     my %ValuesHash = 
 8602:         (
 8603:          $id.'.title'  => &escape($Title),
 8604:          $id.'.xlabel' => &escape($xlabel),
 8605:          $id.'.ylabel' => &escape($ylabel),
 8606:          $id.'.labels' => join(',',@$Xlabels),
 8607:          $id.'.PlotType' => 'XY',
 8608:          $id.'.NumSets' => 2,
 8609:          $id.'.two_axes' => 1,
 8610:          $id.'.y1_max_value' => $Max1,
 8611:          $id.'.y1_min_value' => $Min1,
 8612:          $id.'.y2_max_value' => $Max2,
 8613:          $id.'.y2_min_value' => $Min2,
 8614:          );
 8615:     #
 8616:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8617:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8618:     }
 8619:     #
 8620:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8621:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8622:         return '';
 8623:     }
 8624:     my $NumSets=1;
 8625:     foreach my $array ($Ydata1,$Ydata2){
 8626:         next if (! ref($array));
 8627:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8628:     }
 8629:     #
 8630:     # Deal with other parameters
 8631:     while (my ($key,$value) = each(%Values)) {
 8632:         $ValuesHash{$id.'.'.$key} = $value;
 8633:     }
 8634:     #
 8635:     &Apache::lonnet::appenv(\%ValuesHash);
 8636:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8637: }
 8638: 
 8639: ############################################################
 8640: ############################################################
 8641: 
 8642: =pod
 8643: 
 8644: =back 
 8645: 
 8646: =head1 Statistics helper routines?  
 8647: 
 8648: Bad place for them but what the hell.
 8649: 
 8650: =over 4
 8651: 
 8652: =item * &chartlink()
 8653: 
 8654: Returns a link to the chart for a specific student.  
 8655: 
 8656: Inputs:
 8657: 
 8658: =over 4
 8659: 
 8660: =item $linktext: The text of the link
 8661: 
 8662: =item $sname: The students username
 8663: 
 8664: =item $sdomain: The students domain
 8665: 
 8666: =back
 8667: 
 8668: =back
 8669: 
 8670: =cut
 8671: 
 8672: ############################################################
 8673: ############################################################
 8674: sub chartlink {
 8675:     my ($linktext, $sname, $sdomain) = @_;
 8676:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8677:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8678:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8679:        '">'.$linktext.'</a>';
 8680: }
 8681: 
 8682: #######################################################
 8683: #######################################################
 8684: 
 8685: =pod
 8686: 
 8687: =head1 Course Environment Routines
 8688: 
 8689: =over 4
 8690: 
 8691: =item * &restore_course_settings()
 8692: 
 8693: =item * &store_course_settings()
 8694: 
 8695: Restores/Store indicated form parameters from the course environment.
 8696: Will not overwrite existing values of the form parameters.
 8697: 
 8698: Inputs: 
 8699: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8700: 
 8701: a hash ref describing the data to be stored.  For example:
 8702:    
 8703: %Save_Parameters = ('Status' => 'scalar',
 8704:     'chartoutputmode' => 'scalar',
 8705:     'chartoutputdata' => 'scalar',
 8706:     'Section' => 'array',
 8707:     'Group' => 'array',
 8708:     'StudentData' => 'array',
 8709:     'Maps' => 'array');
 8710: 
 8711: Returns: both routines return nothing
 8712: 
 8713: =back
 8714: 
 8715: =cut
 8716: 
 8717: #######################################################
 8718: #######################################################
 8719: sub store_course_settings {
 8720:     return &store_settings($env{'request.course.id'},@_);
 8721: }
 8722: 
 8723: sub store_settings {
 8724:     # save to the environment
 8725:     # appenv the same items, just to be safe
 8726:     my $udom  = $env{'user.domain'};
 8727:     my $uname = $env{'user.name'};
 8728:     my ($context,$prefix,$Settings) = @_;
 8729:     my %SaveHash;
 8730:     my %AppHash;
 8731:     while (my ($setting,$type) = each(%$Settings)) {
 8732:         my $basename = join('.','internal',$context,$prefix,$setting);
 8733:         my $envname = 'environment.'.$basename;
 8734:         if (exists($env{'form.'.$setting})) {
 8735:             # Save this value away
 8736:             if ($type eq 'scalar' &&
 8737:                 (! exists($env{$envname}) || 
 8738:                  $env{$envname} ne $env{'form.'.$setting})) {
 8739:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8740:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8741:             } elsif ($type eq 'array') {
 8742:                 my $stored_form;
 8743:                 if (ref($env{'form.'.$setting})) {
 8744:                     $stored_form = join(',',
 8745:                                         map {
 8746:                                             &escape($_);
 8747:                                         } sort(@{$env{'form.'.$setting}}));
 8748:                 } else {
 8749:                     $stored_form = 
 8750:                         &escape($env{'form.'.$setting});
 8751:                 }
 8752:                 # Determine if the array contents are the same.
 8753:                 if ($stored_form ne $env{$envname}) {
 8754:                     $SaveHash{$basename} = $stored_form;
 8755:                     $AppHash{$envname}   = $stored_form;
 8756:                 }
 8757:             }
 8758:         }
 8759:     }
 8760:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8761:                                           $udom,$uname);
 8762:     if ($put_result !~ /^(ok|delayed)/) {
 8763:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8764:                                  'got error:'.$put_result);
 8765:     }
 8766:     # Make sure these settings stick around in this session, too
 8767:     &Apache::lonnet::appenv(\%AppHash);
 8768:     return;
 8769: }
 8770: 
 8771: sub restore_course_settings {
 8772:     return &restore_settings($env{'request.course.id'},@_);
 8773: }
 8774: 
 8775: sub restore_settings {
 8776:     my ($context,$prefix,$Settings) = @_;
 8777:     while (my ($setting,$type) = each(%$Settings)) {
 8778:         next if (exists($env{'form.'.$setting}));
 8779:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8780:             '.'.$setting;
 8781:         if (exists($env{$envname})) {
 8782:             if ($type eq 'scalar') {
 8783:                 $env{'form.'.$setting} = $env{$envname};
 8784:             } elsif ($type eq 'array') {
 8785:                 $env{'form.'.$setting} = [ 
 8786:                                            map { 
 8787:                                                &unescape($_); 
 8788:                                            } split(',',$env{$envname})
 8789:                                            ];
 8790:             }
 8791:         }
 8792:     }
 8793: }
 8794: 
 8795: #######################################################
 8796: #######################################################
 8797: 
 8798: =pod
 8799: 
 8800: =head1 Domain E-mail Routines  
 8801: 
 8802: =over 4
 8803: 
 8804: =item * &build_recipient_list()
 8805: 
 8806: Build recipient lists for four types of e-mail:
 8807: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 8808: (d) Help requests, generated by
 8809: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 8810: 
 8811: Inputs:
 8812: defmail (scalar - email address of default recipient), 
 8813: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8814: defdom (domain for which to retrieve configuration settings),
 8815: origmail (scalar - email address of recipient from loncapa.conf, 
 8816: i.e., predates configuration by DC via domainprefs.pm 
 8817: 
 8818: Returns: comma separated list of addresses to which to send e-mail.
 8819: 
 8820: =back
 8821: 
 8822: =cut
 8823: 
 8824: ############################################################
 8825: ############################################################
 8826: sub build_recipient_list {
 8827:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8828:     my @recipients;
 8829:     my $otheremails;
 8830:     my %domconfig =
 8831:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8832:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8833:         if (exists($domconfig{'contacts'}{$mailing})) {
 8834:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8835:                 my @contacts = ('adminemail','supportemail');
 8836:                 foreach my $item (@contacts) {
 8837:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 8838:                         my $addr = $domconfig{'contacts'}{$item}; 
 8839:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 8840:                             push(@recipients,$addr);
 8841:                         }
 8842:                     }
 8843:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8844:                 }
 8845:             }
 8846:         } elsif ($origmail ne '') {
 8847:             push(@recipients,$origmail);
 8848:         }
 8849:     } elsif ($origmail ne '') {
 8850:         push(@recipients,$origmail);
 8851:     }
 8852:     if (defined($defmail)) {
 8853:         if ($defmail ne '') {
 8854:             push(@recipients,$defmail);
 8855:         }
 8856:     }
 8857:     if ($otheremails) {
 8858:         my @others;
 8859:         if ($otheremails =~ /,/) {
 8860:             @others = split(/,/,$otheremails);
 8861:         } else {
 8862:             push(@others,$otheremails);
 8863:         }
 8864:         foreach my $addr (@others) {
 8865:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8866:                 push(@recipients,$addr);
 8867:             }
 8868:         }
 8869:     }
 8870:     my $recipientlist = join(',',@recipients); 
 8871:     return $recipientlist;
 8872: }
 8873: 
 8874: ############################################################
 8875: ############################################################
 8876: 
 8877: =pod
 8878: 
 8879: =head1 Course Catalog Routines
 8880: 
 8881: =over 4
 8882: 
 8883: =item * &gather_categories()
 8884: 
 8885: Converts category definitions - keys of categories hash stored in  
 8886: coursecategories in configuration.db on the primary library server in a 
 8887: domain - to an array.  Also generates javascript and idx hash used to 
 8888: generate Domain Coordinator interface for editing Course Categories.
 8889: 
 8890: Inputs:
 8891: 
 8892: categories (reference to hash of category definitions).
 8893: 
 8894: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8895:       categories and subcategories).
 8896: 
 8897: idx (reference to hash of counters used in Domain Coordinator interface for 
 8898:       editing Course Categories).
 8899: 
 8900: jsarray (reference to array of categories used to create Javascript arrays for
 8901:          Domain Coordinator interface for editing Course Categories).
 8902: 
 8903: Returns: nothing
 8904: 
 8905: Side effects: populates cats, idx and jsarray. 
 8906: 
 8907: =cut
 8908: 
 8909: sub gather_categories {
 8910:     my ($categories,$cats,$idx,$jsarray) = @_;
 8911:     my %counters;
 8912:     my $num = 0;
 8913:     foreach my $item (keys(%{$categories})) {
 8914:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8915:         if ($container eq '' && $depth == 0) {
 8916:             $cats->[$depth][$categories->{$item}] = $cat;
 8917:         } else {
 8918:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8919:         }
 8920:         my ($escitem,$tail) = split(/:/,$item,2);
 8921:         if ($counters{$tail} eq '') {
 8922:             $counters{$tail} = $num;
 8923:             $num ++;
 8924:         }
 8925:         if (ref($idx) eq 'HASH') {
 8926:             $idx->{$item} = $counters{$tail};
 8927:         }
 8928:         if (ref($jsarray) eq 'ARRAY') {
 8929:             push(@{$jsarray->[$counters{$tail}]},$item);
 8930:         }
 8931:     }
 8932:     return;
 8933: }
 8934: 
 8935: =pod
 8936: 
 8937: =item * &extract_categories()
 8938: 
 8939: Used to generate breadcrumb trails for course categories.
 8940: 
 8941: Inputs:
 8942: 
 8943: categories (reference to hash of category definitions).
 8944: 
 8945: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8946:       categories and subcategories).
 8947: 
 8948: trails (reference to array of breacrumb trails for each category).
 8949: 
 8950: allitems (reference to hash - key is category key 
 8951:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8952: 
 8953: idx (reference to hash of counters used in Domain Coordinator interface for
 8954:       editing Course Categories).
 8955: 
 8956: jsarray (reference to array of categories used to create Javascript arrays for
 8957:          Domain Coordinator interface for editing Course Categories).
 8958: 
 8959: subcats (reference to hash of arrays containing all subcategories within each 
 8960:          category, -recursive)
 8961: 
 8962: Returns: nothing
 8963: 
 8964: Side effects: populates trails and allitems hash references.
 8965: 
 8966: =cut
 8967: 
 8968: sub extract_categories {
 8969:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8970:     if (ref($categories) eq 'HASH') {
 8971:         &gather_categories($categories,$cats,$idx,$jsarray);
 8972:         if (ref($cats->[0]) eq 'ARRAY') {
 8973:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8974:                 my $name = $cats->[0][$i];
 8975:                 my $item = &escape($name).'::0';
 8976:                 my $trailstr;
 8977:                 if ($name eq 'instcode') {
 8978:                     $trailstr = &mt('Official courses (with institutional codes)');
 8979:                 } else {
 8980:                     $trailstr = $name;
 8981:                 }
 8982:                 if ($allitems->{$item} eq '') {
 8983:                     push(@{$trails},$trailstr);
 8984:                     $allitems->{$item} = scalar(@{$trails})-1;
 8985:                 }
 8986:                 my @parents = ($name);
 8987:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8988:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8989:                         my $category = $cats->[1]{$name}[$j];
 8990:                         if (ref($subcats) eq 'HASH') {
 8991:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8992:                         }
 8993:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8994:                     }
 8995:                 } else {
 8996:                     if (ref($subcats) eq 'HASH') {
 8997:                         $subcats->{$item} = [];
 8998:                     }
 8999:                 }
 9000:             }
 9001:         }
 9002:     }
 9003:     return;
 9004: }
 9005: 
 9006: =pod
 9007: 
 9008: =item *&recurse_categories()
 9009: 
 9010: Recursively used to generate breadcrumb trails for course categories.
 9011: 
 9012: Inputs:
 9013: 
 9014: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9015:       categories and subcategories).
 9016: 
 9017: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9018: 
 9019: category (current course category, for which breadcrumb trail is being generated).
 9020: 
 9021: trails (reference to array of breadcrumb trails for each category).
 9022: 
 9023: allitems (reference to hash - key is category key
 9024:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9025: 
 9026: parents (array containing containers directories for current category, 
 9027:          back to top level). 
 9028: 
 9029: Returns: nothing
 9030: 
 9031: Side effects: populates trails and allitems hash references
 9032: 
 9033: =cut
 9034: 
 9035: sub recurse_categories {
 9036:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9037:     my $shallower = $depth - 1;
 9038:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9039:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9040:             my $name = $cats->[$depth]{$category}[$k];
 9041:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9042:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9043:             if ($allitems->{$item} eq '') {
 9044:                 push(@{$trails},$trailstr);
 9045:                 $allitems->{$item} = scalar(@{$trails})-1;
 9046:             }
 9047:             my $deeper = $depth+1;
 9048:             push(@{$parents},$category);
 9049:             if (ref($subcats) eq 'HASH') {
 9050:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9051:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9052:                     my $higher;
 9053:                     if ($j > 0) {
 9054:                         $higher = &escape($parents->[$j]).':'.
 9055:                                   &escape($parents->[$j-1]).':'.$j;
 9056:                     } else {
 9057:                         $higher = &escape($parents->[$j]).'::'.$j;
 9058:                     }
 9059:                     push(@{$subcats->{$higher}},$subcat);
 9060:                 }
 9061:             }
 9062:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9063:                                 $subcats);
 9064:             pop(@{$parents});
 9065:         }
 9066:     } else {
 9067:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9068:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9069:         if ($allitems->{$item} eq '') {
 9070:             push(@{$trails},$trailstr);
 9071:             $allitems->{$item} = scalar(@{$trails})-1;
 9072:         }
 9073:     }
 9074:     return;
 9075: }
 9076: 
 9077: =pod
 9078: 
 9079: =item *&assign_categories_table()
 9080: 
 9081: Create a datatable for display of hierarchical categories in a domain,
 9082: with checkboxes to allow a course to be categorized. 
 9083: 
 9084: Inputs:
 9085: 
 9086: cathash - reference to hash of categories defined for the domain (from
 9087:           configuration.db)
 9088: 
 9089: currcat - scalar with an & separated list of categories assigned to a course. 
 9090: 
 9091: Returns: $output (markup to be displayed) 
 9092: 
 9093: =cut
 9094: 
 9095: sub assign_categories_table {
 9096:     my ($cathash,$currcat) = @_;
 9097:     my $output;
 9098:     if (ref($cathash) eq 'HASH') {
 9099:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9100:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9101:         $maxdepth = scalar(@cats);
 9102:         if (@cats > 0) {
 9103:             my $itemcount = 0;
 9104:             if (ref($cats[0]) eq 'ARRAY') {
 9105:                 $output = &Apache::loncommon::start_data_table();
 9106:                 my @currcategories;
 9107:                 if ($currcat ne '') {
 9108:                     @currcategories = split('&',$currcat);
 9109:                 }
 9110:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9111:                     my $parent = $cats[0][$i];
 9112:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9113:                     next if ($parent eq 'instcode');
 9114:                     my $item = &escape($parent).'::0';
 9115:                     my $checked = '';
 9116:                     if (@currcategories > 0) {
 9117:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9118:                             $checked = ' checked="checked"';
 9119:                         }
 9120:                     }
 9121:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9122:                                '<input type="checkbox" name="usecategory" value="'.
 9123:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9124:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9125:                     my $depth = 1;
 9126:                     push(@path,$parent);
 9127:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9128:                     pop(@path);
 9129:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9130:                     $itemcount ++;
 9131:                 }
 9132:                 $output .= &Apache::loncommon::end_data_table();
 9133:             }
 9134:         }
 9135:     }
 9136:     return $output;
 9137: }
 9138: 
 9139: =pod
 9140: 
 9141: =item *&assign_category_rows()
 9142: 
 9143: Create a datatable row for display of nested categories in a domain,
 9144: with checkboxes to allow a course to be categorized,called recursively.
 9145: 
 9146: Inputs:
 9147: 
 9148: itemcount - track row number for alternating colors
 9149: 
 9150: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9151:       categories and subcategories.
 9152: 
 9153: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9154: 
 9155: parent - parent of current category item
 9156: 
 9157: path - Array containing all categories back up through the hierarchy from the
 9158:        current category to the top level.
 9159: 
 9160: currcategories - reference to array of current categories assigned to the course
 9161: 
 9162: Returns: $output (markup to be displayed).
 9163: 
 9164: =cut
 9165: 
 9166: sub assign_category_rows {
 9167:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9168:     my ($text,$name,$item,$chgstr);
 9169:     if (ref($cats) eq 'ARRAY') {
 9170:         my $maxdepth = scalar(@{$cats});
 9171:         if (ref($cats->[$depth]) eq 'HASH') {
 9172:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9173:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9174:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9175:                 $text .= '<td><table class="LC_datatable">';
 9176:                 for (my $j=0; $j<$numchildren; $j++) {
 9177:                     $name = $cats->[$depth]{$parent}[$j];
 9178:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9179:                     my $deeper = $depth+1;
 9180:                     my $checked = '';
 9181:                     if (ref($currcategories) eq 'ARRAY') {
 9182:                         if (@{$currcategories} > 0) {
 9183:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9184:                                 $checked = ' checked="checked"';
 9185:                             }
 9186:                         }
 9187:                     }
 9188:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9189:                              '<input type="checkbox" name="usecategory" value="'.
 9190:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9191:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9192:                              '</td><td>';
 9193:                     if (ref($path) eq 'ARRAY') {
 9194:                         push(@{$path},$name);
 9195:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9196:                         pop(@{$path});
 9197:                     }
 9198:                     $text .= '</td></tr>';
 9199:                 }
 9200:                 $text .= '</table></td>';
 9201:             }
 9202:         }
 9203:     }
 9204:     return $text;
 9205: }
 9206: 
 9207: ############################################################
 9208: ############################################################
 9209: 
 9210: 
 9211: sub commit_customrole {
 9212:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9213:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9214:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9215:                          ($end?', ending '.localtime($end):'').': <b>'.
 9216:               &Apache::lonnet::assigncustomrole(
 9217:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9218:                  '</b><br />';
 9219:     return $output;
 9220: }
 9221: 
 9222: sub commit_standardrole {
 9223:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9224:     my ($output,$logmsg,$linefeed);
 9225:     if ($context eq 'auto') {
 9226:         $linefeed = "\n";
 9227:     } else {
 9228:         $linefeed = "<br />\n";
 9229:     }  
 9230:     if ($three eq 'st') {
 9231:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9232:                                          $one,$two,$sec,$context);
 9233:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9234:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9235:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9236:         } else {
 9237:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9238:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9239:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9240:             if ($context eq 'auto') {
 9241:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9242:             } else {
 9243:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9244:                &mt('Add to classlist').': <b>ok</b>';
 9245:             }
 9246:             $output .= $linefeed;
 9247:         }
 9248:     } else {
 9249:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9250:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9251:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9252:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9253:         if ($context eq 'auto') {
 9254:             $output .= $result.$linefeed;
 9255:         } else {
 9256:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9257:         }
 9258:     }
 9259:     return $output;
 9260: }
 9261: 
 9262: sub commit_studentrole {
 9263:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9264:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9265:     if ($context eq 'auto') {
 9266:         $linefeed = "\n";
 9267:     } else {
 9268:         $linefeed = '<br />'."\n";
 9269:     }
 9270:     if (defined($one) && defined($two)) {
 9271:         my $cid=$one.'_'.$two;
 9272:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9273:         my $secchange = 0;
 9274:         my $expire_role_result;
 9275:         my $modify_section_result;
 9276:         if ($oldsec ne '-1') { 
 9277:             if ($oldsec ne $sec) {
 9278:                 $secchange = 1;
 9279:                 my $now = time;
 9280:                 my $uurl='/'.$cid;
 9281:                 $uurl=~s/\_/\//g;
 9282:                 if ($oldsec) {
 9283:                     $uurl.='/'.$oldsec;
 9284:                 }
 9285:                 $oldsecurl = $uurl;
 9286:                 $expire_role_result = 
 9287:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9288:                 if ($env{'request.course.sec'} ne '') { 
 9289:                     if ($expire_role_result eq 'refused') {
 9290:                         my @roles = ('st');
 9291:                         my @statuses = ('previous');
 9292:                         my @roledoms = ($one);
 9293:                         my $withsec = 1;
 9294:                         my %roleshash = 
 9295:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9296:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9297:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9298:                             my ($oldstart,$oldend) = 
 9299:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9300:                             if ($oldend > 0 && $oldend <= $now) {
 9301:                                 $expire_role_result = 'ok';
 9302:                             }
 9303:                         }
 9304:                     }
 9305:                 }
 9306:                 $result = $expire_role_result;
 9307:             }
 9308:         }
 9309:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9310:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9311:             if ($modify_section_result =~ /^ok/) {
 9312:                 if ($secchange == 1) {
 9313:                     if ($sec eq '') {
 9314:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9315:                     } else {
 9316:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9317:                     }
 9318:                 } elsif ($oldsec eq '-1') {
 9319:                     if ($sec eq '') {
 9320:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9321:                     } else {
 9322:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9323:                     }
 9324:                 } else {
 9325:                     if ($sec eq '') {
 9326:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9327:                     } else {
 9328:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9329:                     }
 9330:                 }
 9331:             } else {
 9332:                 if ($secchange) {       
 9333:                     $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
 9334:                 } else {
 9335:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9336:                 }
 9337:             }
 9338:             $result = $modify_section_result;
 9339:         } elsif ($secchange == 1) {
 9340:             if ($oldsec eq '') {
 9341:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9342:             } else {
 9343:                 $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
 9344:             }
 9345:             if ($expire_role_result eq 'refused') {
 9346:                 my $newsecurl = '/'.$cid;
 9347:                 $newsecurl =~ s/\_/\//g;
 9348:                 if ($sec ne '') {
 9349:                     $newsecurl.='/'.$sec;
 9350:                 }
 9351:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9352:                     if ($sec eq '') {
 9353:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
 9354:                     } else {
 9355:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
 9356:                     }
 9357:                 }
 9358:             }
 9359:         }
 9360:     } else {
 9361:         $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
 9362:         $result = "error: incomplete course id\n";
 9363:     }
 9364:     return $result;
 9365: }
 9366: 
 9367: ############################################################
 9368: ############################################################
 9369: 
 9370: sub check_clone {
 9371:     my ($args,$linefeed) = @_;
 9372:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9373:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9374:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9375:     my $clonemsg;
 9376:     my $can_clone = 0;
 9377: 
 9378:     if ($clonehome eq 'no_host') {
 9379:         $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});     
 9380:     } else {
 9381: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9382: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9383: 	    $can_clone = 1;
 9384: 	} else {
 9385: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9386: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9387: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9388:             if (grep(/^\*$/,@cloners)) {
 9389:                 $can_clone = 1;
 9390:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9391:                 $can_clone = 1;
 9392:             } else {
 9393: 	        my %roleshash =
 9394: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9395: 					 $args->{'ccdomain'},
 9396:                                          'userroles',['active'],['cc'],
 9397: 					 [$args->{'clonedomain'}]);
 9398: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9399: 		    $can_clone = 1;
 9400: 	        } else {
 9401:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
 9402: 	        }
 9403: 	    }
 9404:         }
 9405:     }
 9406:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9407: }
 9408: 
 9409: sub construct_course {
 9410:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9411:     my $outcome;
 9412:     my $linefeed =  '<br />'."\n";
 9413:     if ($context eq 'auto') {
 9414:         $linefeed = "\n";
 9415:     }
 9416: 
 9417: #
 9418: # Are we cloning?
 9419: #
 9420:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9421:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9422: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9423: 	if ($context ne 'auto') {
 9424:             if ($clonemsg ne '') {
 9425: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9426:             }
 9427: 	}
 9428: 	$outcome .= $clonemsg.$linefeed;
 9429: 
 9430:         if (!$can_clone) {
 9431: 	    return (0,$outcome);
 9432: 	}
 9433:     }
 9434: 
 9435: #
 9436: # Open course
 9437: #
 9438:     my $crstype = lc($args->{'crstype'});
 9439:     my %cenv=();
 9440:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9441:                                              $args->{'cdescr'},
 9442:                                              $args->{'curl'},
 9443:                                              $args->{'course_home'},
 9444:                                              $args->{'nonstandard'},
 9445:                                              $args->{'crscode'},
 9446:                                              $args->{'ccuname'}.':'.
 9447:                                              $args->{'ccdomain'},
 9448:                                              $args->{'crstype'});
 9449: 
 9450:     # Note: The testing routines depend on this being output; see 
 9451:     # Utils::Course. This needs to at least be output as a comment
 9452:     # if anyone ever decides to not show this, and Utils::Course::new
 9453:     # will need to be suitably modified.
 9454:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9455: #
 9456: # Check if created correctly
 9457: #
 9458:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9459:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9460:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9461: 
 9462: #
 9463: # Do the cloning
 9464: #   
 9465:     if ($can_clone && $cloneid) {
 9466: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9467: 	if ($context ne 'auto') {
 9468: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9469: 	}
 9470: 	$outcome .= $clonemsg.$linefeed;
 9471: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9472: # Copy all files
 9473: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9474: # Restore URL
 9475: 	$cenv{'url'}=$oldcenv{'url'};
 9476: # Restore title
 9477: 	$cenv{'description'}=$oldcenv{'description'};
 9478: # Mark as cloned
 9479: 	$cenv{'clonedfrom'}=$cloneid;
 9480: # Need to clone grading mode
 9481:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9482:         $cenv{'grading'}=$newenv{'grading'};
 9483: # Do not clone these environment entries
 9484:         &Apache::lonnet::del('environment',
 9485:                   ['default_enrollment_start_date',
 9486:                    'default_enrollment_end_date',
 9487:                    'question.email',
 9488:                    'policy.email',
 9489:                    'comment.email',
 9490:                    'pch.users.denied',
 9491:                    'plc.users.denied',
 9492:                    'hidefromcat',
 9493:                    'categories'],
 9494:                    $$crsudom,$$crsunum);
 9495:     }
 9496: 
 9497: #
 9498: # Set environment (will override cloned, if existing)
 9499: #
 9500:     my @sections = ();
 9501:     my @xlists = ();
 9502:     if ($args->{'crstype'}) {
 9503:         $cenv{'type'}=$args->{'crstype'};
 9504:     }
 9505:     if ($args->{'crsid'}) {
 9506:         $cenv{'courseid'}=$args->{'crsid'};
 9507:     }
 9508:     if ($args->{'crscode'}) {
 9509:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9510:     }
 9511:     if ($args->{'crsquota'} ne '') {
 9512:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9513:     } else {
 9514:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9515:     }
 9516:     if ($args->{'ccuname'}) {
 9517:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9518:                                         ':'.$args->{'ccdomain'};
 9519:     } else {
 9520:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9521:     }
 9522:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9523:     if ($args->{'crssections'}) {
 9524:         $cenv{'internal.sectionnums'} = '';
 9525:         if ($args->{'crssections'} =~ m/,/) {
 9526:             @sections = split/,/,$args->{'crssections'};
 9527:         } else {
 9528:             $sections[0] = $args->{'crssections'};
 9529:         }
 9530:         if (@sections > 0) {
 9531:             foreach my $item (@sections) {
 9532:                 my ($sec,$gp) = split/:/,$item;
 9533:                 my $class = $args->{'crscode'}.$sec;
 9534:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9535:                 $cenv{'internal.sectionnums'} .= $item.',';
 9536:                 unless ($addcheck eq 'ok') {
 9537:                     push @badclasses, $class;
 9538:                 }
 9539:             }
 9540:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9541:         }
 9542:     }
 9543: # do not hide course coordinator from staff listing, 
 9544: # even if privileged
 9545:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9546: # add crosslistings
 9547:     if ($args->{'crsxlist'}) {
 9548:         $cenv{'internal.crosslistings'}='';
 9549:         if ($args->{'crsxlist'} =~ m/,/) {
 9550:             @xlists = split/,/,$args->{'crsxlist'};
 9551:         } else {
 9552:             $xlists[0] = $args->{'crsxlist'};
 9553:         }
 9554:         if (@xlists > 0) {
 9555:             foreach my $item (@xlists) {
 9556:                 my ($xl,$gp) = split/:/,$item;
 9557:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9558:                 $cenv{'internal.crosslistings'} .= $item.',';
 9559:                 unless ($addcheck eq 'ok') {
 9560:                     push @badclasses, $xl;
 9561:                 }
 9562:             }
 9563:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9564:         }
 9565:     }
 9566:     if ($args->{'autoadds'}) {
 9567:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9568:     }
 9569:     if ($args->{'autodrops'}) {
 9570:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9571:     }
 9572: # check for notification of enrollment changes
 9573:     my @notified = ();
 9574:     if ($args->{'notify_owner'}) {
 9575:         if ($args->{'ccuname'} ne '') {
 9576:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9577:         }
 9578:     }
 9579:     if ($args->{'notify_dc'}) {
 9580:         if ($uname ne '') { 
 9581:             push(@notified,$uname.':'.$udom);
 9582:         }
 9583:     }
 9584:     if (@notified > 0) {
 9585:         my $notifylist;
 9586:         if (@notified > 1) {
 9587:             $notifylist = join(',',@notified);
 9588:         } else {
 9589:             $notifylist = $notified[0];
 9590:         }
 9591:         $cenv{'internal.notifylist'} = $notifylist;
 9592:     }
 9593:     if (@badclasses > 0) {
 9594:         my %lt=&Apache::lonlocal::texthash(
 9595:                 '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',
 9596:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9597:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9598:         );
 9599:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9600:                            ' ('.$lt{'adby'}.')';
 9601:         if ($context eq 'auto') {
 9602:             $outcome .= $badclass_msg.$linefeed;
 9603:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9604:             foreach my $item (@badclasses) {
 9605:                 if ($context eq 'auto') {
 9606:                     $outcome .= " - $item\n";
 9607:                 } else {
 9608:                     $outcome .= "<li>$item</li>\n";
 9609:                 }
 9610:             }
 9611:             if ($context eq 'auto') {
 9612:                 $outcome .= $linefeed;
 9613:             } else {
 9614:                 $outcome .= "</ul><br /><br /></div>\n";
 9615:             }
 9616:         } 
 9617:     }
 9618:     if ($args->{'no_end_date'}) {
 9619:         $args->{'endaccess'} = 0;
 9620:     }
 9621:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9622:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9623:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9624:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9625:     if ($args->{'showphotos'}) {
 9626:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9627:     }
 9628:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9629:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9630:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9631:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9632:             my $krb_msg = &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'); 
 9633:             if ($context eq 'auto') {
 9634:                 $outcome .= $krb_msg;
 9635:             } else {
 9636:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9637:             }
 9638:             $outcome .= $linefeed;
 9639:         }
 9640:     }
 9641:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9642:        if ($args->{'setpolicy'}) {
 9643:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9644:        }
 9645:        if ($args->{'setcontent'}) {
 9646:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9647:        }
 9648:     }
 9649:     if ($args->{'reshome'}) {
 9650: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9651: 	$cenv{'reshome'}=~s/\/+$/\//;
 9652:     }
 9653: #
 9654: # course has keyed access
 9655: #
 9656:     if ($args->{'setkeys'}) {
 9657:        $cenv{'keyaccess'}='yes';
 9658:     }
 9659: # if specified, key authority is not course, but user
 9660: # only active if keyaccess is yes
 9661:     if ($args->{'keyauth'}) {
 9662: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9663: 	$user = &LONCAPA::clean_username($user);
 9664: 	$domain = &LONCAPA::clean_username($domain);
 9665: 	if ($user ne '' && $domain ne '') {
 9666: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9667: 	}
 9668:     }
 9669: 
 9670:     if ($args->{'disresdis'}) {
 9671:         $cenv{'pch.roles.denied'}='st';
 9672:     }
 9673:     if ($args->{'disablechat'}) {
 9674:         $cenv{'plc.roles.denied'}='st';
 9675:     }
 9676: 
 9677:     # Record we've not yet viewed the Course Initialization Helper for this 
 9678:     # course
 9679:     $cenv{'course.helper.not.run'} = 1;
 9680:     #
 9681:     # Use new Randomseed
 9682:     #
 9683:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9684:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9685:     #
 9686:     # The encryption code and receipt prefix for this course
 9687:     #
 9688:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9689:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9690:     #
 9691:     # By default, use standard grading
 9692:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9693: 
 9694:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9695:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9696: #
 9697: # Open all assignments
 9698: #
 9699:     if ($args->{'openall'}) {
 9700:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9701:        my %storecontent = ($storeunder         => time,
 9702:                            $storeunder.'.type' => 'date_start');
 9703:        
 9704:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9705:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9706:    }
 9707: #
 9708: # Set first page
 9709: #
 9710:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9711: 	    || ($cloneid)) {
 9712: 	use LONCAPA::map;
 9713: 	$outcome .= &mt('Setting first resource').': ';
 9714: 
 9715: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9716:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9717: 
 9718:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9719:         my $title; my $url;
 9720:         if ($args->{'firstres'} eq 'syl') {
 9721: 	    $title=&mt('Syllabus');
 9722:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9723:         } else {
 9724:             $title=&mt('Navigate Contents');
 9725:             $url='/adm/navmaps';
 9726:         }
 9727: 
 9728:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9729: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9730: 
 9731: 	if ($errtext) { $fatal=2; }
 9732:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9733:     }
 9734: 
 9735:     return (1,$outcome);
 9736: }
 9737: 
 9738: ############################################################
 9739: ############################################################
 9740: 
 9741: sub course_type {
 9742:     my ($cid) = @_;
 9743:     if (!defined($cid)) {
 9744:         $cid = $env{'request.course.id'};
 9745:     }
 9746:     if (defined($env{'course.'.$cid.'.type'})) {
 9747:         return $env{'course.'.$cid.'.type'};
 9748:     } else {
 9749:         return 'Course';
 9750:     }
 9751: }
 9752: 
 9753: sub group_term {
 9754:     my $crstype = &course_type();
 9755:     my %names = (
 9756:                   'Course' => 'group',
 9757:                   'Group' => 'team',
 9758:                 );
 9759:     return $names{$crstype};
 9760: }
 9761: 
 9762: sub icon {
 9763:     my ($file)=@_;
 9764:     my $curfext = lc((split(/\./,$file))[-1]);
 9765:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9766:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9767:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9768: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9769: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9770: 	            $curfext.".gif") {
 9771: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9772: 		$curfext.".gif";
 9773: 	}
 9774:     }
 9775:     return &lonhttpdurl($iconname);
 9776: } 
 9777: 
 9778: sub lonhttpdurl {
 9779: #
 9780: # Had been used for "small fry" static images on separate port 8080.
 9781: # Modify here if lightweight http functionality desired again.
 9782: # Currently eliminated due to increasing firewall issues.
 9783: #
 9784:     my ($url)=@_;
 9785:     return $url;
 9786: }
 9787: 
 9788: sub connection_aborted {
 9789:     my ($r)=@_;
 9790:     $r->print(" ");$r->rflush();
 9791:     my $c = $r->connection;
 9792:     return $c->aborted();
 9793: }
 9794: 
 9795: #    Escapes strings that may have embedded 's that will be put into
 9796: #    strings as 'strings'.
 9797: sub escape_single {
 9798:     my ($input) = @_;
 9799:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9800:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9801:     return $input;
 9802: }
 9803: 
 9804: #  Same as escape_single, but escape's "'s  This 
 9805: #  can be used for  "strings"
 9806: sub escape_double {
 9807:     my ($input) = @_;
 9808:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9809:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9810:     return $input;
 9811: }
 9812:  
 9813: #   Escapes the last element of a full URL.
 9814: sub escape_url {
 9815:     my ($url)   = @_;
 9816:     my @urlslices = split(/\//, $url,-1);
 9817:     my $lastitem = &escape(pop(@urlslices));
 9818:     return join('/',@urlslices).'/'.$lastitem;
 9819: }
 9820: 
 9821: # -------------------------------------------------------- Initliaze user login
 9822: sub init_user_environment {
 9823:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9824:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9825: 
 9826:     my $public=($username eq 'public' && $domain eq 'public');
 9827: 
 9828: # See if old ID present, if so, remove
 9829: 
 9830:     my ($filename,$cookie,$userroles);
 9831:     my $now=time;
 9832: 
 9833:     if ($public) {
 9834: 	my $max_public=100;
 9835: 	my $oldest;
 9836: 	my $oldest_time=0;
 9837: 	for(my $next=1;$next<=$max_public;$next++) {
 9838: 	    if (-e $lonids."/publicuser_$next.id") {
 9839: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9840: 		if ($mtime<$oldest_time || !$oldest_time) {
 9841: 		    $oldest_time=$mtime;
 9842: 		    $oldest=$next;
 9843: 		}
 9844: 	    } else {
 9845: 		$cookie="publicuser_$next";
 9846: 		last;
 9847: 	    }
 9848: 	}
 9849: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9850:     } else {
 9851: 	# if this isn't a robot, kill any existing non-robot sessions
 9852: 	if (!$args->{'robot'}) {
 9853: 	    opendir(DIR,$lonids);
 9854: 	    while ($filename=readdir(DIR)) {
 9855: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9856: 		    unlink($lonids.'/'.$filename);
 9857: 		}
 9858: 	    }
 9859: 	    closedir(DIR);
 9860: 	}
 9861: # Give them a new cookie
 9862: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9863: 		                   : $now.$$.int(rand(10000)));
 9864: 	$cookie="$username\_$id\_$domain\_$authhost";
 9865:     
 9866: # Initialize roles
 9867: 
 9868: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9869:     }
 9870: # ------------------------------------ Check browser type and MathML capability
 9871: 
 9872:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9873:         $clientunicode,$clientos) = &decode_user_agent($r);
 9874: 
 9875: # -------------------------------------- Any accessibility options to remember?
 9876:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9877: 	foreach my $option ('imagesuppress','appletsuppress',
 9878: 			    'embedsuppress','fontenhance','blackwhite') {
 9879: 	    if ($form->{$option} eq 'true') {
 9880: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9881: 				     $domain,$username);
 9882: 	    } else {
 9883: 		&Apache::lonnet::del('environment',[$option],
 9884: 				     $domain,$username);
 9885: 	    }
 9886: 	}
 9887:     }
 9888: # ------------------------------------------------------------- Get environment
 9889: 
 9890:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9891:     my ($tmp) = keys(%userenv);
 9892:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9893: 	# default remote control to off
 9894: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9895:     } else {
 9896: 	undef(%userenv);
 9897:     }
 9898:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9899: 	$form->{'interface'}=$userenv{'interface'};
 9900:     }
 9901:     $env{'environment.remote'}=$userenv{'remote'};
 9902:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9903: 
 9904: # --------------- Do not trust query string to be put directly into environment
 9905:     foreach my $option ('imagesuppress','appletsuppress',
 9906: 			'embedsuppress','fontenhance','blackwhite',
 9907: 			'interface','localpath','localres') {
 9908: 	$form->{$option}=~s/[\n\r\=]//gs;
 9909:     }
 9910: # --------------------------------------------------------- Write first profile
 9911: 
 9912:     {
 9913: 	my %initial_env = 
 9914: 	    ("user.name"          => $username,
 9915: 	     "user.domain"        => $domain,
 9916: 	     "user.home"          => $authhost,
 9917: 	     "browser.type"       => $clientbrowser,
 9918: 	     "browser.version"    => $clientversion,
 9919: 	     "browser.mathml"     => $clientmathml,
 9920: 	     "browser.unicode"    => $clientunicode,
 9921: 	     "browser.os"         => $clientos,
 9922: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9923: 	     "request.course.fn"  => '',
 9924: 	     "request.course.uri" => '',
 9925: 	     "request.course.sec" => '',
 9926: 	     "request.role"       => 'cm',
 9927: 	     "request.role.adv"   => $env{'user.adv'},
 9928: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9929: 
 9930:         if ($form->{'localpath'}) {
 9931: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9932: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9933:         }
 9934: 	
 9935: 	if ($public) {
 9936: 	    $initial_env{"environment.remote"} = "off";
 9937: 	}
 9938: 	if ($form->{'interface'}) {
 9939: 	    $form->{'interface'}=~s/\W//gs;
 9940: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9941: 	    $env{'browser.interface'}=$form->{'interface'};
 9942: 	    foreach my $option ('imagesuppress','appletsuppress',
 9943: 				'embedsuppress','fontenhance','blackwhite') {
 9944: 		if (($form->{$option} eq 'true') ||
 9945: 		    ($userenv{$option} eq 'on')) {
 9946: 		    $initial_env{"browser.$option"} = "on";
 9947: 		}
 9948: 	    }
 9949: 	}
 9950: 
 9951:         foreach my $tool ('aboutme','blog','portfolio') {
 9952:             $userenv{'availabletools.'.$tool} = 
 9953:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9954:         }
 9955: 
 9956:         foreach my $crstype ('official','unofficial') {
 9957:             $userenv{'canrequest.'.$crstype} =
 9958:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
 9959:                                                   'reload','requestcourses');
 9960:         }
 9961: 
 9962: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9963: 	
 9964: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9965: 		 &GDBM_WRCREAT(),0640)) {
 9966: 	    &_add_to_env(\%disk_env,\%initial_env);
 9967: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9968: 	    &_add_to_env(\%disk_env,$userroles);
 9969: 	    if (ref($args->{'extra_env'})) {
 9970: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9971: 	    }
 9972: 	    untie(%disk_env);
 9973: 	} else {
 9974: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
 9975: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
 9976: 	    return 'error: '.$!;
 9977: 	}
 9978:     }
 9979:     $env{'request.role'}='cm';
 9980:     $env{'request.role.adv'}=$env{'user.adv'};
 9981:     $env{'browser.type'}=$clientbrowser;
 9982: 
 9983:     return $cookie;
 9984: 
 9985: }
 9986: 
 9987: sub _add_to_env {
 9988:     my ($idf,$env_data,$prefix) = @_;
 9989:     if (ref($env_data) eq 'HASH') {
 9990:         while (my ($key,$value) = each(%$env_data)) {
 9991: 	    $idf->{$prefix.$key} = $value;
 9992: 	    $env{$prefix.$key}   = $value;
 9993:         }
 9994:     }
 9995: }
 9996: 
 9997: # --- Get the symbolic name of a problem and the url
 9998: sub get_symb {
 9999:     my ($request,$silent) = @_;
10000:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10001:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10002:     if ($symb eq '') {
10003:         if (!$silent) {
10004:             $request->print("Unable to handle ambiguous references:$url:.");
10005:             return ();
10006:         }
10007:     }
10008:     &Apache::lonenc::check_decrypt(\$symb);
10009:     return ($symb);
10010: }
10011: 
10012: # --------------------------------------------------------------Get annotation
10013: 
10014: sub get_annotation {
10015:     my ($symb,$enc) = @_;
10016: 
10017:     my $key = $symb;
10018:     if (!$enc) {
10019:         $key =
10020:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10021:     }
10022:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10023:     return $annotation{$key};
10024: }
10025: 
10026: sub clean_symb {
10027:     my ($symb,$delete_enc) = @_;
10028: 
10029:     &Apache::lonenc::check_decrypt(\$symb);
10030:     my $enc = $env{'request.enc'};
10031:     if ($delete_enc) {
10032:         delete($env{'request.enc'});
10033:     }
10034: 
10035:     return ($symb,$enc);
10036: }
10037: 
10038: =pod
10039: 
10040: =back
10041: 
10042: =cut
10043: 
10044: 1;
10045: __END__;
10046: 

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