File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.736: download - view: text, annotated - select for diffs
Wed Jan 28 13:49:50 2009 UTC (15 years, 4 months ago) by muellerd
Branches: MAIN
CVS tags: HEAD
deleted style ".LC_docs_course_commands" because it's no longer used
: ----------------------------------------------------------------------

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.736 2009/01/28 13:49:50 muellerd 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 .= 
  928:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  929:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
  930:     }
  931: 
  932:     # Add the graphic
  933:     my $title = &mt('Online Help');
  934:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  935:     $template .= <<"ENDTEMPLATE";
  936:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  937: ENDTEMPLATE
  938:     if ($text ne '') { $template.='</td></tr></table>' };
  939:     return $template;
  940: 
  941: }
  942: 
  943: # This is a quicky function for Latex cheatsheet editing, since it 
  944: # appears in at least four places
  945: sub helpLatexCheatsheet {
  946:     my ($topic,$text,$not_author) = @_;
  947:     my $out;
  948:     my $addOther = '';
  949:     if ($topic) {
  950: 	$addOther = &Apache::loncommon::help_open_topic($topic,$text,
  951: 						       undef, undef, 600).
  952: 							   '</td><td>';
  953:     }
  954:     $out = '<table><tr><td>'.
  955: 	   $addOther .
  956: 	   &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  957: 					       undef,undef,600).
  958: 	   '</td><td>'.
  959: 	   &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
  960: 					       undef,undef,600).
  961: 	   '</td>';
  962:     unless ($not_author) {
  963:         $out .= '<td>'.
  964: 	        &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
  965: 	                                            undef,undef,600).
  966: 	        '</td>';
  967:     }
  968:     $out .= '</tr></table>';
  969:     return $out;
  970: }
  971: 
  972: sub general_help {
  973:     my $helptopic='Student_Intro';
  974:     if ($env{'request.role'}=~/^(ca|au)/) {
  975: 	$helptopic='Authoring_Intro';
  976:     } elsif ($env{'request.role'}=~/^cc/) {
  977: 	$helptopic='Course_Coordination_Intro';
  978:     } elsif ($env{'request.role'}=~/^dc/) {
  979:         $helptopic='Domain_Coordination_Intro';
  980:     }
  981:     return $helptopic;
  982: }
  983: 
  984: sub update_help_link {
  985:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  986:     my $origurl = $ENV{'REQUEST_URI'};
  987:     $origurl=~s|^/~|/priv/|;
  988:     my $timestamp = time;
  989:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  990:         $$datum = &escape($$datum);
  991:     }
  992: 
  993:     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";
  994:     my $output .= <<"ENDOUTPUT";
  995: <script type="text/javascript">
  996: banner_link = '$banner_link';
  997: </script>
  998: ENDOUTPUT
  999:     return $output;
 1000: }
 1001: 
 1002: # now just updates the help link and generates a blue icon
 1003: sub help_open_menu {
 1004:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1005: 	= @_;    
 1006:     $stayOnPage = 0 if (not defined $stayOnPage);
 1007:     # only use pop-up help (stayOnPage == 0)
 1008:     # if environment.remote is on (using remote control UI)
 1009:     if ($env{'browser.interface'} eq 'textual' ||
 1010:     	$env{'environment.remote'} eq 'off' ) {
 1011:         $stayOnPage=1;
 1012:     }
 1013:     my $output;
 1014:     if ($component_help) {
 1015: 	if (!$text) {
 1016: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1017: 				       $width,$height);
 1018: 	} else {
 1019: 	    my $help_text;
 1020: 	    $help_text=&unescape($topic);
 1021: 	    $output='<table><tr><td>'.
 1022: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1023: 				 $width,$height).'</td></tr></table>';
 1024: 	}
 1025:     }
 1026:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1027:     return $output.$banner_link;
 1028: }
 1029: 
 1030: sub top_nav_help {
 1031:     my ($text) = @_;
 1032:     $text = &mt($text);
 1033:     my $stay_on_page = 
 1034: 	($env{'browser.interface'}  eq 'textual' ||
 1035: 	 $env{'environment.remote'} eq 'off' );
 1036:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1037: 	                     : "javascript:helpMenu('open')";
 1038:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1039: 
 1040:     my $title = &mt('Get help');
 1041: 
 1042:     return <<"END";
 1043: $banner_link
 1044:  <a href="$link" title="$title">$text</a>
 1045: END
 1046: }
 1047: 
 1048: sub help_menu_js {
 1049:     my ($text) = @_;
 1050: 
 1051:     my $stayOnPage = 
 1052: 	($env{'browser.interface'}  eq 'textual' ||
 1053: 	 $env{'environment.remote'} eq 'off' );
 1054: 
 1055:     my $width = 620;
 1056:     my $height = 600;
 1057:     my $helptopic=&general_help();
 1058:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1059:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1060:     my $start_page =
 1061:         &Apache::loncommon::start_page('Help Menu', undef,
 1062: 				       {'frameset'    => 1,
 1063: 					'js_ready'    => 1,
 1064: 					'add_entries' => {
 1065: 					    'border' => '0',
 1066: 					    'rows'   => "110,*",},});
 1067:     my $end_page =
 1068:         &Apache::loncommon::end_page({'frameset' => 1,
 1069: 				      'js_ready' => 1,});
 1070: 
 1071:     my $template .= <<"ENDTEMPLATE";
 1072: <script type="text/javascript">
 1073: // <!-- BEGIN LON-CAPA Internal
 1074: // <![CDATA[
 1075: var banner_link = '';
 1076: function helpMenu(target) {
 1077:     var caller = this;
 1078:     if (target == 'open') {
 1079:         var newWindow = null;
 1080:         try {
 1081:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1082:         }
 1083:         catch(error) {
 1084:             writeHelp(caller);
 1085:             return;
 1086:         }
 1087:         if (newWindow) {
 1088:             caller = newWindow;
 1089:         }
 1090:     }
 1091:     writeHelp(caller);
 1092:     return;
 1093: }
 1094: function writeHelp(caller) {
 1095:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1096:     caller.document.close()
 1097:     caller.focus()
 1098: }
 1099: // ]]>
 1100: // END LON-CAPA Internal -->
 1101: </script>
 1102: ENDTEMPLATE
 1103:     return $template;
 1104: }
 1105: 
 1106: sub help_open_bug {
 1107:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1108:     unless ($env{'user.adv'}) { return ''; }
 1109:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1110:     $text = "" if (not defined $text);
 1111:     $stayOnPage = 0 if (not defined $stayOnPage);
 1112:     if ($env{'browser.interface'} eq 'textual' ||
 1113: 	$env{'environment.remote'} eq 'off' ) {
 1114: 	$stayOnPage=1;
 1115:     }
 1116:     $width = 600 if (not defined $width);
 1117:     $height = 600 if (not defined $height);
 1118: 
 1119:     $topic=~s/\W+/\+/g;
 1120:     my $link='';
 1121:     my $template='';
 1122:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1123: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1124:     if (!$stayOnPage)
 1125:     {
 1126: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1127:     }
 1128:     else
 1129:     {
 1130: 	$link = $url;
 1131:     }
 1132:     # Add the text
 1133:     if ($text ne "")
 1134:     {
 1135: 	$template .= 
 1136:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1137:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1138:     }
 1139: 
 1140:     # Add the graphic
 1141:     my $title = &mt('Report a Bug');
 1142:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1143:     $template .= <<"ENDTEMPLATE";
 1144:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1145: ENDTEMPLATE
 1146:     if ($text ne '') { $template.='</td></tr></table>' };
 1147:     return $template;
 1148: 
 1149: }
 1150: 
 1151: sub help_open_faq {
 1152:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1153:     unless ($env{'user.adv'}) { return ''; }
 1154:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1155:     $text = "" if (not defined $text);
 1156:     $stayOnPage = 0 if (not defined $stayOnPage);
 1157:     if ($env{'browser.interface'} eq 'textual' ||
 1158: 	$env{'environment.remote'} eq 'off' ) {
 1159: 	$stayOnPage=1;
 1160:     }
 1161:     $width = 350 if (not defined $width);
 1162:     $height = 400 if (not defined $height);
 1163: 
 1164:     $topic=~s/\W+/\+/g;
 1165:     my $link='';
 1166:     my $template='';
 1167:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1168:     if (!$stayOnPage)
 1169:     {
 1170: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1171:     }
 1172:     else
 1173:     {
 1174: 	$link = $url;
 1175:     }
 1176: 
 1177:     # Add the text
 1178:     if ($text ne "")
 1179:     {
 1180: 	$template .= 
 1181:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1182:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1183:     }
 1184: 
 1185:     # Add the graphic
 1186:     my $title = &mt('View the FAQ');
 1187:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1188:     $template .= <<"ENDTEMPLATE";
 1189:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1190: ENDTEMPLATE
 1191:     if ($text ne '') { $template.='</td></tr></table>' };
 1192:     return $template;
 1193: 
 1194: }
 1195: 
 1196: ###############################################################
 1197: ###############################################################
 1198: 
 1199: =pod
 1200: 
 1201: =item * &change_content_javascript():
 1202: 
 1203: This and the next function allow you to create small sections of an
 1204: otherwise static HTML page that you can update on the fly with
 1205: Javascript, even in Netscape 4.
 1206: 
 1207: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1208: must be written to the HTML page once. It will prove the Javascript
 1209: function "change(name, content)". Calling the change function with the
 1210: name of the section 
 1211: you want to update, matching the name passed to C<changable_area>, and
 1212: the new content you want to put in there, will put the content into
 1213: that area.
 1214: 
 1215: B<Note>: Netscape 4 only reserves enough space for the changable area
 1216: to contain room for the original contents. You need to "make space"
 1217: for whatever changes you wish to make, and be B<sure> to check your
 1218: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1219: it's adequate for updating a one-line status display, but little more.
 1220: This script will set the space to 100% width, so you only need to
 1221: worry about height in Netscape 4.
 1222: 
 1223: Modern browsers are much less limiting, and if you can commit to the
 1224: user not using Netscape 4, this feature may be used freely with
 1225: pretty much any HTML.
 1226: 
 1227: =cut
 1228: 
 1229: sub change_content_javascript {
 1230:     # If we're on Netscape 4, we need to use Layer-based code
 1231:     if ($env{'browser.type'} eq 'netscape' &&
 1232: 	$env{'browser.version'} =~ /^4\./) {
 1233: 	return (<<NETSCAPE4);
 1234: 	function change(name, content) {
 1235: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1236: 	    doc.open();
 1237: 	    doc.write(content);
 1238: 	    doc.close();
 1239: 	}
 1240: NETSCAPE4
 1241:     } else {
 1242: 	# Otherwise, we need to use semi-standards-compliant code
 1243: 	# (technically, "innerHTML" isn't standard but the equivalent
 1244: 	# is really scary, and every useful browser supports it
 1245: 	return (<<DOMBASED);
 1246: 	function change(name, content) {
 1247: 	    element = document.getElementById(name);
 1248: 	    element.innerHTML = content;
 1249: 	}
 1250: DOMBASED
 1251:     }
 1252: }
 1253: 
 1254: =pod
 1255: 
 1256: =item * &changable_area($name,$origContent):
 1257: 
 1258: This provides a "changable area" that can be modified on the fly via
 1259: the Javascript code provided in C<change_content_javascript>. $name is
 1260: the name you will use to reference the area later; do not repeat the
 1261: same name on a given HTML page more then once. $origContent is what
 1262: the area will originally contain, which can be left blank.
 1263: 
 1264: =cut
 1265: 
 1266: sub changable_area {
 1267:     my ($name, $origContent) = @_;
 1268: 
 1269:     if ($env{'browser.type'} eq 'netscape' &&
 1270: 	$env{'browser.version'} =~ /^4\./) {
 1271: 	# If this is netscape 4, we need to use the Layer tag
 1272: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1273:     } else {
 1274: 	return "<span id='$name'>$origContent</span>";
 1275:     }
 1276: }
 1277: 
 1278: =pod
 1279: 
 1280: =item * &viewport_geometry_js 
 1281: 
 1282: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1283: 
 1284: =cut
 1285: 
 1286: 
 1287: sub viewport_geometry_js { 
 1288:     return <<"GEOMETRY";
 1289: var Geometry = {};
 1290: function init_geometry() {
 1291:     if (Geometry.init) { return };
 1292:     Geometry.init=1;
 1293:     if (window.innerHeight) {
 1294:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1295:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1296:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1297:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1298:     }
 1299:     else if (document.documentElement && document.documentElement.clientHeight) {
 1300:         Geometry.getViewportHeight =
 1301:             function() { return document.documentElement.clientHeight; };
 1302:         Geometry.getViewportWidth =
 1303:             function() { return document.documentElement.clientWidth; };
 1304: 
 1305:         Geometry.getHorizontalScroll =
 1306:             function() { return document.documentElement.scrollLeft; };
 1307:         Geometry.getVerticalScroll =
 1308:             function() { return document.documentElement.scrollTop; };
 1309:     }
 1310:     else if (document.body.clientHeight) {
 1311:         Geometry.getViewportHeight =
 1312:             function() { return document.body.clientHeight; };
 1313:         Geometry.getViewportWidth =
 1314:             function() { return document.body.clientWidth; };
 1315:         Geometry.getHorizontalScroll =
 1316:             function() { return document.body.scrollLeft; };
 1317:         Geometry.getVerticalScroll =
 1318:             function() { return document.body.scrollTop; };
 1319:     }
 1320: }
 1321: 
 1322: GEOMETRY
 1323: }
 1324: 
 1325: =pod
 1326: 
 1327: =item * &viewport_size_js()
 1328: 
 1329: 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. 
 1330: 
 1331: =cut
 1332: 
 1333: sub viewport_size_js {
 1334:     my $geometry = &viewport_geometry_js();
 1335:     return <<"DIMS";
 1336: 
 1337: $geometry
 1338: 
 1339: function getViewportDims(width,height) {
 1340:     init_geometry();
 1341:     width.value = Geometry.getViewportWidth();
 1342:     height.value = Geometry.getViewportHeight();
 1343:     return;
 1344: }
 1345: 
 1346: DIMS
 1347: }
 1348: 
 1349: =pod
 1350: 
 1351: =item * &resize_textarea_js()
 1352: 
 1353: emits the needed javascript to resize a textarea to be as big as possible
 1354: 
 1355: creates a function resize_textrea that takes two IDs first should be
 1356: the id of the element to resize, second should be the id of a div that
 1357: surrounds everything that comes after the textarea, this routine needs
 1358: to be attached to the <body> for the onload and onresize events.
 1359: 
 1360: =back
 1361: 
 1362: =cut
 1363: 
 1364: sub resize_textarea_js {
 1365:     my $geometry = &viewport_geometry_js();
 1366:     return <<"RESIZE";
 1367:     <script type="text/javascript">
 1368: $geometry
 1369: 
 1370: function getX(element) {
 1371:     var x = 0;
 1372:     while (element) {
 1373: 	x += element.offsetLeft;
 1374: 	element = element.offsetParent;
 1375:     }
 1376:     return x;
 1377: }
 1378: function getY(element) {
 1379:     var y = 0;
 1380:     while (element) {
 1381: 	y += element.offsetTop;
 1382: 	element = element.offsetParent;
 1383:     }
 1384:     return y;
 1385: }
 1386: 
 1387: 
 1388: function resize_textarea(textarea_id,bottom_id) {
 1389:     init_geometry();
 1390:     var textarea        = document.getElementById(textarea_id);
 1391:     //alert(textarea);
 1392: 
 1393:     var textarea_top    = getY(textarea);
 1394:     var textarea_height = textarea.offsetHeight;
 1395:     var bottom          = document.getElementById(bottom_id);
 1396:     var bottom_top      = getY(bottom);
 1397:     var bottom_height   = bottom.offsetHeight;
 1398:     var window_height   = Geometry.getViewportHeight();
 1399:     var fudge           = 23;
 1400:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1401:     if (new_height < 300) {
 1402: 	new_height = 300;
 1403:     }
 1404:     textarea.style.height=new_height+'px';
 1405: }
 1406: </script>
 1407: RESIZE
 1408: 
 1409: }
 1410: 
 1411: =pod
 1412: 
 1413: =head1 Excel and CSV file utility routines
 1414: 
 1415: =over 4
 1416: 
 1417: =cut
 1418: 
 1419: ###############################################################
 1420: ###############################################################
 1421: 
 1422: =pod
 1423: 
 1424: =item * &csv_translate($text) 
 1425: 
 1426: Translate $text to allow it to be output as a 'comma separated values' 
 1427: format.
 1428: 
 1429: =cut
 1430: 
 1431: ###############################################################
 1432: ###############################################################
 1433: sub csv_translate {
 1434:     my $text = shift;
 1435:     $text =~ s/\"/\"\"/g;
 1436:     $text =~ s/\n/ /g;
 1437:     return $text;
 1438: }
 1439: 
 1440: ###############################################################
 1441: ###############################################################
 1442: 
 1443: =pod
 1444: 
 1445: =item * &define_excel_formats()
 1446: 
 1447: Define some commonly used Excel cell formats.
 1448: 
 1449: Currently supported formats:
 1450: 
 1451: =over 4
 1452: 
 1453: =item header
 1454: 
 1455: =item bold
 1456: 
 1457: =item h1
 1458: 
 1459: =item h2
 1460: 
 1461: =item h3
 1462: 
 1463: =item h4
 1464: 
 1465: =item i
 1466: 
 1467: =item date
 1468: 
 1469: =back
 1470: 
 1471: Inputs: $workbook
 1472: 
 1473: Returns: $format, a hash reference.
 1474: 
 1475: =cut
 1476: 
 1477: ###############################################################
 1478: ###############################################################
 1479: sub define_excel_formats {
 1480:     my ($workbook) = @_;
 1481:     my $format;
 1482:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1483:                                                 bottom    => 1,
 1484:                                                 align     => 'center');
 1485:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1486:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1487:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1488:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1489:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1490:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1491:     $format->{'date'} = $workbook->add_format(num_format=>
 1492:                                             'mm/dd/yyyy hh:mm:ss');
 1493:     return $format;
 1494: }
 1495: 
 1496: ###############################################################
 1497: ###############################################################
 1498: 
 1499: =pod
 1500: 
 1501: =item * &create_workbook()
 1502: 
 1503: Create an Excel worksheet.  If it fails, output message on the
 1504: request object and return undefs.
 1505: 
 1506: Inputs: Apache request object
 1507: 
 1508: Returns (undef) on failure, 
 1509:     Excel worksheet object, scalar with filename, and formats 
 1510:     from &Apache::loncommon::define_excel_formats on success
 1511: 
 1512: =cut
 1513: 
 1514: ###############################################################
 1515: ###############################################################
 1516: sub create_workbook {
 1517:     my ($r) = @_;
 1518:         #
 1519:     # Create the excel spreadsheet
 1520:     my $filename = '/prtspool/'.
 1521:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1522:         time.'_'.rand(1000000000).'.xls';
 1523:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1524:     if (! defined($workbook)) {
 1525:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1526:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1527:                             "This error has been logged.  ".
 1528:                             "Please alert your LON-CAPA administrator").
 1529:                   '</p>');
 1530:         return (undef);
 1531:     }
 1532:     #
 1533:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1534:     #
 1535:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1536:     return ($workbook,$filename,$format);
 1537: }
 1538: 
 1539: ###############################################################
 1540: ###############################################################
 1541: 
 1542: =pod
 1543: 
 1544: =item * &create_text_file()
 1545: 
 1546: Create a file to write to and eventually make available to the user.
 1547: If file creation fails, outputs an error message on the request object and 
 1548: return undefs.
 1549: 
 1550: Inputs: Apache request object, and file suffix
 1551: 
 1552: Returns (undef) on failure, 
 1553:     Filehandle and filename on success.
 1554: 
 1555: =cut
 1556: 
 1557: ###############################################################
 1558: ###############################################################
 1559: sub create_text_file {
 1560:     my ($r,$suffix) = @_;
 1561:     if (! defined($suffix)) { $suffix = 'txt'; };
 1562:     my $fh;
 1563:     my $filename = '/prtspool/'.
 1564:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1565:         time.'_'.rand(1000000000).'.'.$suffix;
 1566:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1567:     if (! defined($fh)) {
 1568:         $r->log_error("Couldn't open $filename for output $!");
 1569:         $r->print(&mt('Problems occurred in creating the output file. '
 1570:                      .'This error has been logged. '
 1571:                      .'Please alert your LON-CAPA administrator.'));
 1572:     }
 1573:     return ($fh,$filename)
 1574: }
 1575: 
 1576: 
 1577: =pod 
 1578: 
 1579: =back
 1580: 
 1581: =cut
 1582: 
 1583: ###############################################################
 1584: ##        Home server <option> list generating code          ##
 1585: ###############################################################
 1586: 
 1587: # ------------------------------------------
 1588: 
 1589: sub domain_select {
 1590:     my ($name,$value,$multiple)=@_;
 1591:     my %domains=map { 
 1592: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1593:     } &Apache::lonnet::all_domains();
 1594:     if ($multiple) {
 1595: 	$domains{''}=&mt('Any domain');
 1596: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1597: 	return &multiple_select_form($name,$value,4,\%domains);
 1598:     } else {
 1599: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1600: 	return &select_form($name,$value,%domains);
 1601:     }
 1602: }
 1603: 
 1604: #-------------------------------------------
 1605: 
 1606: =pod
 1607: 
 1608: =head1 Routines for form select boxes
 1609: 
 1610: =over 4
 1611: 
 1612: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1613: 
 1614: Returns a string containing a <select> element int multiple mode
 1615: 
 1616: 
 1617: Args:
 1618:   $name - name of the <select> element
 1619:   $value - scalar or array ref of values that should already be selected
 1620:   $size - number of rows long the select element is
 1621:   $hash - the elements should be 'option' => 'shown text'
 1622:           (shown text should already have been &mt())
 1623:   $order - (optional) array ref of the order to show the elements in
 1624: 
 1625: =cut
 1626: 
 1627: #-------------------------------------------
 1628: sub multiple_select_form {
 1629:     my ($name,$value,$size,$hash,$order)=@_;
 1630:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1631:     my $output='';
 1632:     if (! defined($size)) {
 1633:         $size = 4;
 1634:         if (scalar(keys(%$hash))<4) {
 1635:             $size = scalar(keys(%$hash));
 1636:         }
 1637:     }
 1638:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1639:     my @order;
 1640:     if (ref($order) eq 'ARRAY')  {
 1641:         @order = @{$order};
 1642:     } else {
 1643:         @order = sort(keys(%$hash));
 1644:     }
 1645:     if (exists($$hash{'select_form_order'})) {
 1646:         @order = @{$$hash{'select_form_order'}};
 1647:     }
 1648:         
 1649:     foreach my $key (@order) {
 1650:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1651:         $output.='selected="selected" ' if ($selected{$key});
 1652:         $output.='>'.$hash->{$key}."</option>\n";
 1653:     }
 1654:     $output.="</select>\n";
 1655:     return $output;
 1656: }
 1657: 
 1658: #-------------------------------------------
 1659: 
 1660: =pod
 1661: 
 1662: =item * &select_form($defdom,$name,%hash)
 1663: 
 1664: Returns a string containing a <select name='$name' size='1'> form to 
 1665: allow a user to select options from a hash option_name => displayed text.  
 1666: See lonrights.pm for an example invocation and use.
 1667: 
 1668: =cut
 1669: 
 1670: #-------------------------------------------
 1671: sub select_form {
 1672:     my ($def,$name,%hash) = @_;
 1673:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1674:     my @keys;
 1675:     if (exists($hash{'select_form_order'})) {
 1676: 	@keys=@{$hash{'select_form_order'}};
 1677:     } else {
 1678: 	@keys=sort(keys(%hash));
 1679:     }
 1680:     foreach my $key (@keys) {
 1681:         $selectform.=
 1682: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1683:             ($key eq $def ? 'selected="selected" ' : '').
 1684:                 ">".&mt($hash{$key})."</option>\n";
 1685:     }
 1686:     $selectform.="</select>";
 1687:     return $selectform;
 1688: }
 1689: 
 1690: # For display filters
 1691: 
 1692: sub display_filter {
 1693:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1694:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1695:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1696: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1697: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1698: 	   '</label></span> <span class="LC_nobreak">'.
 1699:            &mt('Filter [_1]',
 1700: 	   &select_form($env{'form.displayfilter'},
 1701: 			'displayfilter',
 1702: 			('currentfolder' => 'Current folder/page',
 1703: 			 'containing' => 'Containing phrase',
 1704: 			 'none' => 'None'))).
 1705: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1706: }
 1707: 
 1708: sub gradeleveldescription {
 1709:     my $gradelevel=shift;
 1710:     my %gradelevels=(0 => 'Not specified',
 1711: 		     1 => 'Grade 1',
 1712: 		     2 => 'Grade 2',
 1713: 		     3 => 'Grade 3',
 1714: 		     4 => 'Grade 4',
 1715: 		     5 => 'Grade 5',
 1716: 		     6 => 'Grade 6',
 1717: 		     7 => 'Grade 7',
 1718: 		     8 => 'Grade 8',
 1719: 		     9 => 'Grade 9',
 1720: 		     10 => 'Grade 10',
 1721: 		     11 => 'Grade 11',
 1722: 		     12 => 'Grade 12',
 1723: 		     13 => 'Grade 13',
 1724: 		     14 => '100 Level',
 1725: 		     15 => '200 Level',
 1726: 		     16 => '300 Level',
 1727: 		     17 => '400 Level',
 1728: 		     18 => 'Graduate Level');
 1729:     return &mt($gradelevels{$gradelevel});
 1730: }
 1731: 
 1732: sub select_level_form {
 1733:     my ($deflevel,$name)=@_;
 1734:     unless ($deflevel) { $deflevel=0; }
 1735:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1736:     for (my $i=0; $i<=18; $i++) {
 1737:         $selectform.="<option value=\"$i\" ".
 1738:             ($i==$deflevel ? 'selected="selected" ' : '').
 1739:                 ">".&gradeleveldescription($i)."</option>\n";
 1740:     }
 1741:     $selectform.="</select>";
 1742:     return $selectform;
 1743: }
 1744: 
 1745: #-------------------------------------------
 1746: 
 1747: =pod
 1748: 
 1749: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
 1750: 
 1751: Returns a string containing a <select name='$name' size='1'> form to 
 1752: allow a user to select the domain to preform an operation in.  
 1753: See loncreateuser.pm for an example invocation and use.
 1754: 
 1755: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1756: selected");
 1757: 
 1758: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
 1759: 
 1760: =cut
 1761: 
 1762: #-------------------------------------------
 1763: sub select_dom_form {
 1764:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
 1765:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1766:     if ($includeempty) { @domains=('',@domains); }
 1767:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1768:     foreach my $dom (@domains) {
 1769:         $selectdomain.="<option value=\"$dom\" ".
 1770:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1771:         if ($showdomdesc) {
 1772:             if ($dom ne '') {
 1773:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1774:                 if ($domdesc ne '') {
 1775:                     $selectdomain .= ' ('.$domdesc.')';
 1776:                 }
 1777:             } 
 1778:         }
 1779:         $selectdomain .= "</option>\n";
 1780:     }
 1781:     $selectdomain.="</select>";
 1782:     return $selectdomain;
 1783: }
 1784: 
 1785: #-------------------------------------------
 1786: 
 1787: =pod
 1788: 
 1789: =item * &home_server_form_item($domain,$name,$defaultflag)
 1790: 
 1791: input: 4 arguments (two required, two optional) - 
 1792:     $domain - domain of new user
 1793:     $name - name of form element
 1794:     $default - Value of 'default' causes a default item to be first 
 1795:                             option, and selected by default. 
 1796:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1797:                             if 1 server found, or default, if 0 found.
 1798: output: returns 2 items: 
 1799: (a) form element which contains either:
 1800:    (i) <select name="$name">
 1801:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1802:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1803:        </select>
 1804:        form item if there are multiple library servers in $domain, or
 1805:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1806:        if there is only one library server in $domain.
 1807: 
 1808: (b) number of library servers found.
 1809: 
 1810: See loncreateuser.pm for example of use.
 1811: 
 1812: =cut
 1813: 
 1814: #-------------------------------------------
 1815: sub home_server_form_item {
 1816:     my ($domain,$name,$default,$hide) = @_;
 1817:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1818:     my $result;
 1819:     my $numlib = keys(%servers);
 1820:     if ($numlib > 1) {
 1821:         $result .= '<select name="'.$name.'" />'."\n";
 1822:         if ($default) {
 1823:             $result .= '<option value="default" selected>'.&mt('default').
 1824:                        '</option>'."\n";
 1825:         }
 1826:         foreach my $hostid (sort(keys(%servers))) {
 1827:             $result.= '<option value="'.$hostid.'">'.
 1828: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1829:         }
 1830:         $result .= '</select>'."\n";
 1831:     } elsif ($numlib == 1) {
 1832:         my $hostid;
 1833:         foreach my $item (keys(%servers)) {
 1834:             $hostid = $item;
 1835:         }
 1836:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1837:                    $hostid.'" />';
 1838:                    if (!$hide) {
 1839:                        $result .= $hostid.' '.$servers{$hostid};
 1840:                    }
 1841:                    $result .= "\n";
 1842:     } elsif ($default) {
 1843:         $result .= '<input type="hidden" name="'.$name.
 1844:                    '" value="default" />';
 1845:                    if (!$hide) {
 1846:                        $result .= &mt('default');
 1847:                    }
 1848:                    $result .= "\n";
 1849:     }
 1850:     return ($result,$numlib);
 1851: }
 1852: 
 1853: =pod
 1854: 
 1855: =back 
 1856: 
 1857: =cut
 1858: 
 1859: ###############################################################
 1860: ##                  Decoding User Agent                      ##
 1861: ###############################################################
 1862: 
 1863: =pod
 1864: 
 1865: =head1 Decoding the User Agent
 1866: 
 1867: =over 4
 1868: 
 1869: =item * &decode_user_agent()
 1870: 
 1871: Inputs: $r
 1872: 
 1873: Outputs:
 1874: 
 1875: =over 4
 1876: 
 1877: =item * $httpbrowser
 1878: 
 1879: =item * $clientbrowser
 1880: 
 1881: =item * $clientversion
 1882: 
 1883: =item * $clientmathml
 1884: 
 1885: =item * $clientunicode
 1886: 
 1887: =item * $clientos
 1888: 
 1889: =back
 1890: 
 1891: =back 
 1892: 
 1893: =cut
 1894: 
 1895: ###############################################################
 1896: ###############################################################
 1897: sub decode_user_agent {
 1898:     my ($r)=@_;
 1899:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1900:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1901:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1902:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1903:     my $clientbrowser='unknown';
 1904:     my $clientversion='0';
 1905:     my $clientmathml='';
 1906:     my $clientunicode='0';
 1907:     for (my $i=0;$i<=$#browsertype;$i++) {
 1908:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1909: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1910: 	    $clientbrowser=$bname;
 1911:             $httpbrowser=~/$vreg/i;
 1912: 	    $clientversion=$1;
 1913:             $clientmathml=($clientversion>=$minv);
 1914:             $clientunicode=($clientversion>=$univ);
 1915: 	}
 1916:     }
 1917:     my $clientos='unknown';
 1918:     if (($httpbrowser=~/linux/i) ||
 1919:         ($httpbrowser=~/unix/i) ||
 1920:         ($httpbrowser=~/ux/i) ||
 1921:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1922:     if (($httpbrowser=~/vax/i) ||
 1923:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1924:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1925:     if (($httpbrowser=~/mac/i) ||
 1926:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1927:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1928:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1929:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1930:             $clientunicode,$clientos,);
 1931: }
 1932: 
 1933: ###############################################################
 1934: ##    Authentication changing form generation subroutines    ##
 1935: ###############################################################
 1936: ##
 1937: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1938: ## hash, and have reasonable default values.
 1939: ##
 1940: ##    formname = the name given in the <form> tag.
 1941: #-------------------------------------------
 1942: 
 1943: =pod
 1944: 
 1945: =head1 Authentication Routines
 1946: 
 1947: =over 4
 1948: 
 1949: =item * &authform_xxxxxx()
 1950: 
 1951: The authform_xxxxxx subroutines provide javascript and html forms which 
 1952: handle some of the conveniences required for authentication forms.  
 1953: This is not an optimal method, but it works.  
 1954: 
 1955: =over 4
 1956: 
 1957: =item * authform_header
 1958: 
 1959: =item * authform_authorwarning
 1960: 
 1961: =item * authform_nochange
 1962: 
 1963: =item * authform_kerberos
 1964: 
 1965: =item * authform_internal
 1966: 
 1967: =item * authform_filesystem
 1968: 
 1969: =back
 1970: 
 1971: See loncreateuser.pm for invocation and use examples.
 1972: 
 1973: =cut
 1974: 
 1975: #-------------------------------------------
 1976: sub authform_header{  
 1977:     my %in = (
 1978:         formname => 'cu',
 1979:         kerb_def_dom => '',
 1980:         @_,
 1981:     );
 1982:     $in{'formname'} = 'document.' . $in{'formname'};
 1983:     my $result='';
 1984: 
 1985: #---------------------------------------------- Code for upper case translation
 1986:     my $Javascript_toUpperCase;
 1987:     unless ($in{kerb_def_dom}) {
 1988:         $Javascript_toUpperCase =<<"END";
 1989:         switch (choice) {
 1990:            case 'krb': currentform.elements[choicearg].value =
 1991:                currentform.elements[choicearg].value.toUpperCase();
 1992:                break;
 1993:            default:
 1994:         }
 1995: END
 1996:     } else {
 1997:         $Javascript_toUpperCase = "";
 1998:     }
 1999: 
 2000:     my $radioval = "'nochange'";
 2001:     if (defined($in{'curr_authtype'})) {
 2002:         if ($in{'curr_authtype'} ne '') {
 2003:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2004:         }
 2005:     }
 2006:     my $argfield = 'null';
 2007:     if (defined($in{'mode'})) {
 2008:         if ($in{'mode'} eq 'modifycourse')  {
 2009:             if (defined($in{'curr_autharg'})) {
 2010:                 if ($in{'curr_autharg'} ne '') {
 2011:                     $argfield = "'$in{'curr_autharg'}'";
 2012:                 }
 2013:             }
 2014:         }
 2015:     }
 2016: 
 2017:     $result.=<<"END";
 2018: var current = new Object();
 2019: current.radiovalue = $radioval;
 2020: current.argfield = $argfield;
 2021: 
 2022: function changed_radio(choice,currentform) {
 2023:     var choicearg = choice + 'arg';
 2024:     // If a radio button in changed, we need to change the argfield
 2025:     if (current.radiovalue != choice) {
 2026:         current.radiovalue = choice;
 2027:         if (current.argfield != null) {
 2028:             currentform.elements[current.argfield].value = '';
 2029:         }
 2030:         if (choice == 'nochange') {
 2031:             current.argfield = null;
 2032:         } else {
 2033:             current.argfield = choicearg;
 2034:             switch(choice) {
 2035:                 case 'krb': 
 2036:                     currentform.elements[current.argfield].value = 
 2037:                         "$in{'kerb_def_dom'}";
 2038:                 break;
 2039:               default:
 2040:                 break;
 2041:             }
 2042:         }
 2043:     }
 2044:     return;
 2045: }
 2046: 
 2047: function changed_text(choice,currentform) {
 2048:     var choicearg = choice + 'arg';
 2049:     if (currentform.elements[choicearg].value !='') {
 2050:         $Javascript_toUpperCase
 2051:         // clear old field
 2052:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2053:             currentform.elements[current.argfield].value = '';
 2054:         }
 2055:         current.argfield = choicearg;
 2056:     }
 2057:     set_auth_radio_buttons(choice,currentform);
 2058:     return;
 2059: }
 2060: 
 2061: function set_auth_radio_buttons(newvalue,currentform) {
 2062:     var i=0;
 2063:     while (i < currentform.login.length) {
 2064:         if (currentform.login[i].value == newvalue) { break; }
 2065:         i++;
 2066:     }
 2067:     if (i == currentform.login.length) {
 2068:         return;
 2069:     }
 2070:     current.radiovalue = newvalue;
 2071:     currentform.login[i].checked = true;
 2072:     return;
 2073: }
 2074: END
 2075:     return $result;
 2076: }
 2077: 
 2078: sub authform_authorwarning{
 2079:     my $result='';
 2080:     $result='<i>'.
 2081:         &mt('As a general rule, only authors or co-authors should be '.
 2082:             'filesystem authenticated '.
 2083:             '(which allows access to the server filesystem).')."</i>\n";
 2084:     return $result;
 2085: }
 2086: 
 2087: sub authform_nochange{  
 2088:     my %in = (
 2089:               formname => 'document.cu',
 2090:               kerb_def_dom => 'MSU.EDU',
 2091:               @_,
 2092:           );
 2093:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2094:     my $result;
 2095:     if (keys(%can_assign) == 0) {
 2096:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2097:     } else {
 2098:         $result = '<label>'.&mt('[_1] Do not change login data',
 2099:                   '<input type="radio" name="login" value="nochange" '.
 2100:                   'checked="checked" onclick="'.
 2101:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2102: 	    '</label>';
 2103:     }
 2104:     return $result;
 2105: }
 2106: 
 2107: sub authform_kerberos {
 2108:     my %in = (
 2109:               formname => 'document.cu',
 2110:               kerb_def_dom => 'MSU.EDU',
 2111:               kerb_def_auth => 'krb4',
 2112:               @_,
 2113:               );
 2114:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2115:         $autharg,$jscall);
 2116:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2117:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2118:        $check5 = ' checked="on"';
 2119:     } else {
 2120:        $check4 = ' checked="on"';
 2121:     }
 2122:     $krbarg = $in{'kerb_def_dom'};
 2123:     if (defined($in{'curr_authtype'})) {
 2124:         if ($in{'curr_authtype'} eq 'krb') {
 2125:             $krbcheck = ' checked="on"';
 2126:             if (defined($in{'mode'})) {
 2127:                 if ($in{'mode'} eq 'modifyuser') {
 2128:                     $krbcheck = '';
 2129:                 }
 2130:             }
 2131:             if (defined($in{'curr_kerb_ver'})) {
 2132:                 if ($in{'curr_krb_ver'} eq '5') {
 2133:                     $check5 = ' checked="on"';
 2134:                     $check4 = '';
 2135:                 } else {
 2136:                     $check4 = ' checked="on"';
 2137:                     $check5 = '';
 2138:                 }
 2139:             }
 2140:             if (defined($in{'curr_autharg'})) {
 2141:                 $krbarg = $in{'curr_autharg'};
 2142:             }
 2143:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2144:                 if (defined($in{'curr_autharg'})) {
 2145:                     $result = 
 2146:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2147:         $in{'curr_autharg'},$krbver);
 2148:                 } else {
 2149:                     $result =
 2150:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2151:                 }
 2152:                 return $result; 
 2153:             }
 2154:         }
 2155:     } else {
 2156:         if ($authnum == 1) {
 2157:             $authtype = '<input type="hidden" name="login" value="krb">';
 2158:         }
 2159:     }
 2160:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2161:         return;
 2162:     } elsif ($authtype eq '') {
 2163:         if (defined($in{'mode'})) {
 2164:             if ($in{'mode'} eq 'modifycourse') {
 2165:                 if ($authnum == 1) {
 2166:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2167:                 }
 2168:             }
 2169:         }
 2170:     }
 2171:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2172:     if ($authtype eq '') {
 2173:         $authtype = '<input type="radio" name="login" value="krb" '.
 2174:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2175:                     $krbcheck.' />';
 2176:     }
 2177:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2178:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2179:          $in{'curr_authtype'} eq 'krb5') ||
 2180:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2181:          $in{'curr_authtype'} eq 'krb4')) {
 2182:         $result .= &mt
 2183:         ('[_1] Kerberos authenticated with domain [_2] '.
 2184:          '[_3] Version 4 [_4] Version 5 [_5]',
 2185:          '<label>'.$authtype,
 2186:          '</label><input type="text" size="10" name="krbarg" '.
 2187:              'value="'.$krbarg.'" '.
 2188:              'onchange="'.$jscall.'" />',
 2189:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2190:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2191: 	 '</label>');
 2192:     } elsif ($can_assign{'krb4'}) {
 2193:         $result .= &mt
 2194:         ('[_1] Kerberos authenticated with domain [_2] '.
 2195:          '[_3] Version 4 [_4]',
 2196:          '<label>'.$authtype,
 2197:          '</label><input type="text" size="10" name="krbarg" '.
 2198:              'value="'.$krbarg.'" '.
 2199:              'onchange="'.$jscall.'" />',
 2200:          '<label><input type="hidden" name="krbver" value="4" />',
 2201:          '</label>');
 2202:     } elsif ($can_assign{'krb5'}) {
 2203:         $result .= &mt
 2204:         ('[_1] Kerberos authenticated with domain [_2] '.
 2205:          '[_3] Version 5 [_4]',
 2206:          '<label>'.$authtype,
 2207:          '</label><input type="text" size="10" name="krbarg" '.
 2208:              'value="'.$krbarg.'" '.
 2209:              'onchange="'.$jscall.'" />',
 2210:          '<label><input type="hidden" name="krbver" value="5" />',
 2211:          '</label>');
 2212:     }
 2213:     return $result;
 2214: }
 2215: 
 2216: sub authform_internal{  
 2217:     my %in = (
 2218:                 formname => 'document.cu',
 2219:                 kerb_def_dom => 'MSU.EDU',
 2220:                 @_,
 2221:                 );
 2222:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2223:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2224:     if (defined($in{'curr_authtype'})) {
 2225:         if ($in{'curr_authtype'} eq 'int') {
 2226:             if ($can_assign{'int'}) {
 2227:                 $intcheck = 'checked="on" ';
 2228:                 if (defined($in{'mode'})) {
 2229:                     if ($in{'mode'} eq 'modifyuser') {
 2230:                         $intcheck = '';
 2231:                     }
 2232:                 }
 2233:                 if (defined($in{'curr_autharg'})) {
 2234:                     $intarg = $in{'curr_autharg'};
 2235:                 }
 2236:             } else {
 2237:                 $result = &mt('Currently internally authenticated.');
 2238:                 return $result;
 2239:             }
 2240:         }
 2241:     } else {
 2242:         if ($authnum == 1) {
 2243:             $authtype = '<input type="hidden" name="login" value="int">';
 2244:         }
 2245:     }
 2246:     if (!$can_assign{'int'}) {
 2247:         return;
 2248:     } elsif ($authtype eq '') {
 2249:         if (defined($in{'mode'})) {
 2250:             if ($in{'mode'} eq 'modifycourse') {
 2251:                 if ($authnum == 1) {
 2252:                     $authtype = '<input type="hidden" name="login" value="int">';
 2253:                 }
 2254:             }
 2255:         }
 2256:     }
 2257:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2258:     if ($authtype eq '') {
 2259:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2260:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2261:     }
 2262:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2263:                $intarg.'" onchange="'.$jscall.'" />';
 2264:     $result = &mt
 2265:         ('[_1] Internally authenticated (with initial password [_2])',
 2266:          '<label>'.$authtype,'</label>'.$autharg);
 2267:     $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>';
 2268:     return $result;
 2269: }
 2270: 
 2271: sub authform_local{  
 2272:     my %in = (
 2273:               formname => 'document.cu',
 2274:               kerb_def_dom => 'MSU.EDU',
 2275:               @_,
 2276:               );
 2277:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2278:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2279:     if (defined($in{'curr_authtype'})) {
 2280:         if ($in{'curr_authtype'} eq 'loc') {
 2281:             if ($can_assign{'loc'}) {
 2282:                 $loccheck = 'checked="on" ';
 2283:                 if (defined($in{'mode'})) {
 2284:                     if ($in{'mode'} eq 'modifyuser') {
 2285:                         $loccheck = '';
 2286:                     }
 2287:                 }
 2288:                 if (defined($in{'curr_autharg'})) {
 2289:                     $locarg = $in{'curr_autharg'};
 2290:                 }
 2291:             } else {
 2292:                 $result = &mt('Currently using local (institutional) authentication.');
 2293:                 return $result;
 2294:             }
 2295:         }
 2296:     } else {
 2297:         if ($authnum == 1) {
 2298:             $authtype = '<input type="hidden" name="login" value="loc">';
 2299:         }
 2300:     }
 2301:     if (!$can_assign{'loc'}) {
 2302:         return;
 2303:     } elsif ($authtype eq '') {
 2304:         if (defined($in{'mode'})) {
 2305:             if ($in{'mode'} eq 'modifycourse') {
 2306:                 if ($authnum == 1) {
 2307:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2308:                 }
 2309:             }
 2310:         }
 2311:     }
 2312:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2313:     if ($authtype eq '') {
 2314:         $authtype = '<input type="radio" name="login" value="loc" '.
 2315:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2316:                     $jscall.'" />';
 2317:     }
 2318:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2319:                $locarg.'" onchange="'.$jscall.'" />';
 2320:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2321:                   '<label>'.$authtype,'</label>'.$autharg);
 2322:     return $result;
 2323: }
 2324: 
 2325: sub authform_filesystem{  
 2326:     my %in = (
 2327:               formname => 'document.cu',
 2328:               kerb_def_dom => 'MSU.EDU',
 2329:               @_,
 2330:               );
 2331:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2332:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2333:     if (defined($in{'curr_authtype'})) {
 2334:         if ($in{'curr_authtype'} eq 'fsys') {
 2335:             if ($can_assign{'fsys'}) {
 2336:                 $fsyscheck = 'checked="on" ';
 2337:                 if (defined($in{'mode'})) {
 2338:                     if ($in{'mode'} eq 'modifyuser') {
 2339:                         $fsyscheck = '';
 2340:                     }
 2341:                 }
 2342:             } else {
 2343:                 $result = &mt('Currently Filesystem Authenticated.');
 2344:                 return $result;
 2345:             }           
 2346:         }
 2347:     } else {
 2348:         if ($authnum == 1) {
 2349:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2350:         }
 2351:     }
 2352:     if (!$can_assign{'fsys'}) {
 2353:         return;
 2354:     } elsif ($authtype eq '') {
 2355:         if (defined($in{'mode'})) {
 2356:             if ($in{'mode'} eq 'modifycourse') {
 2357:                 if ($authnum == 1) {
 2358:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2359:                 }
 2360:             }
 2361:         }
 2362:     }
 2363:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2364:     if ($authtype eq '') {
 2365:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2366:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2367:                     $jscall.'" />';
 2368:     }
 2369:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2370:                ' onchange="'.$jscall.'" />';
 2371:     $result = &mt
 2372:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2373:          '<label><input type="radio" name="login" value="fsys" '.
 2374:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2375:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2376:                   'onchange="'.$jscall.'" />');
 2377:     return $result;
 2378: }
 2379: 
 2380: sub get_assignable_auth {
 2381:     my ($dom) = @_;
 2382:     if ($dom eq '') {
 2383:         $dom = $env{'request.role.domain'};
 2384:     }
 2385:     my %can_assign = (
 2386:                           krb4 => 1,
 2387:                           krb5 => 1,
 2388:                           int  => 1,
 2389:                           loc  => 1,
 2390:                      );
 2391:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2392:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2393:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2394:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2395:             my $context;
 2396:             if ($env{'request.role'} =~ /^au/) {
 2397:                 $context = 'author';
 2398:             } elsif ($env{'request.role'} =~ /^dc/) {
 2399:                 $context = 'domain';
 2400:             } elsif ($env{'request.course.id'}) {
 2401:                 $context = 'course';
 2402:             }
 2403:             if ($context) {
 2404:                 if (ref($authhash->{$context}) eq 'HASH') {
 2405:                    %can_assign = %{$authhash->{$context}}; 
 2406:                 }
 2407:             }
 2408:         }
 2409:     }
 2410:     my $authnum = 0;
 2411:     foreach my $key (keys(%can_assign)) {
 2412:         if ($can_assign{$key}) {
 2413:             $authnum ++;
 2414:         }
 2415:     }
 2416:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2417:         $authnum --;
 2418:     }
 2419:     return ($authnum,%can_assign);
 2420: }
 2421: 
 2422: ###############################################################
 2423: ##    Get Kerberos Defaults for Domain                 ##
 2424: ###############################################################
 2425: ##
 2426: ## Returns default kerberos version and an associated argument
 2427: ## as listed in file domain.tab. If not listed, provides
 2428: ## appropriate default domain and kerberos version.
 2429: ##
 2430: #-------------------------------------------
 2431: 
 2432: =pod
 2433: 
 2434: =item * &get_kerberos_defaults()
 2435: 
 2436: get_kerberos_defaults($target_domain) returns the default kerberos
 2437: version and domain. If not found, it defaults to version 4 and the 
 2438: domain of the server.
 2439: 
 2440: =over 4
 2441: 
 2442: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2443: 
 2444: =back
 2445: 
 2446: =back
 2447: 
 2448: =cut
 2449: 
 2450: #-------------------------------------------
 2451: sub get_kerberos_defaults {
 2452:     my $domain=shift;
 2453:     my ($krbdef,$krbdefdom);
 2454:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2455:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2456:         $krbdef = $domdefaults{'auth_def'};
 2457:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2458:     } else {
 2459:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2460:         my $krbdefdom=$1;
 2461:         $krbdefdom=~tr/a-z/A-Z/;
 2462:         $krbdef = "krb4";
 2463:     }
 2464:     return ($krbdef,$krbdefdom);
 2465: }
 2466: 
 2467: 
 2468: ###############################################################
 2469: ##                Thesaurus Functions                        ##
 2470: ###############################################################
 2471: 
 2472: =pod
 2473: 
 2474: =head1 Thesaurus Functions
 2475: 
 2476: =over 4
 2477: 
 2478: =item * &initialize_keywords()
 2479: 
 2480: Initializes the package variable %Keywords if it is empty.  Uses the
 2481: package variable $thesaurus_db_file.
 2482: 
 2483: =cut
 2484: 
 2485: ###################################################
 2486: 
 2487: sub initialize_keywords {
 2488:     return 1 if (scalar keys(%Keywords));
 2489:     # If we are here, %Keywords is empty, so fill it up
 2490:     #   Make sure the file we need exists...
 2491:     if (! -e $thesaurus_db_file) {
 2492:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2493:                                  " failed because it does not exist");
 2494:         return 0;
 2495:     }
 2496:     #   Set up the hash as a database
 2497:     my %thesaurus_db;
 2498:     if (! tie(%thesaurus_db,'GDBM_File',
 2499:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2500:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2501:                                  $thesaurus_db_file);
 2502:         return 0;
 2503:     } 
 2504:     #  Get the average number of appearances of a word.
 2505:     my $avecount = $thesaurus_db{'average.count'};
 2506:     #  Put keywords (those that appear > average) into %Keywords
 2507:     while (my ($word,$data)=each (%thesaurus_db)) {
 2508:         my ($count,undef) = split /:/,$data;
 2509:         $Keywords{$word}++ if ($count > $avecount);
 2510:     }
 2511:     untie %thesaurus_db;
 2512:     # Remove special values from %Keywords.
 2513:     foreach my $value ('total.count','average.count') {
 2514:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2515:   }
 2516:     return 1;
 2517: }
 2518: 
 2519: ###################################################
 2520: 
 2521: =pod
 2522: 
 2523: =item * &keyword($word)
 2524: 
 2525: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2526: than the average number of times in the thesaurus database.  Calls 
 2527: &initialize_keywords
 2528: 
 2529: =cut
 2530: 
 2531: ###################################################
 2532: 
 2533: sub keyword {
 2534:     return if (!&initialize_keywords());
 2535:     my $word=lc(shift());
 2536:     $word=~s/\W//g;
 2537:     return exists($Keywords{$word});
 2538: }
 2539: 
 2540: ###############################################################
 2541: 
 2542: =pod 
 2543: 
 2544: =item * &get_related_words()
 2545: 
 2546: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2547: an array of words.  If the keyword is not in the thesaurus, an empty array
 2548: will be returned.  The order of the words returned is determined by the
 2549: database which holds them.
 2550: 
 2551: Uses global $thesaurus_db_file.
 2552: 
 2553: =cut
 2554: 
 2555: ###############################################################
 2556: sub get_related_words {
 2557:     my $keyword = shift;
 2558:     my %thesaurus_db;
 2559:     if (! -e $thesaurus_db_file) {
 2560:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2561:                                  "failed because the file does not exist");
 2562:         return ();
 2563:     }
 2564:     if (! tie(%thesaurus_db,'GDBM_File',
 2565:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2566:         return ();
 2567:     } 
 2568:     my @Words=();
 2569:     my $count=0;
 2570:     if (exists($thesaurus_db{$keyword})) {
 2571: 	# The first element is the number of times
 2572: 	# the word appears.  We do not need it now.
 2573: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2574: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2575: 	my $threshold=$mostfrequentcount/10;
 2576:         foreach my $possibleword (@RelatedWords) {
 2577:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2578:             if ($wordcount>$threshold) {
 2579: 		push(@Words,$word);
 2580:                 $count++;
 2581:                 if ($count>10) { last; }
 2582: 	    }
 2583:         }
 2584:     }
 2585:     untie %thesaurus_db;
 2586:     return @Words;
 2587: }
 2588: 
 2589: =pod
 2590: 
 2591: =back
 2592: 
 2593: =cut
 2594: 
 2595: # -------------------------------------------------------------- Plaintext name
 2596: =pod
 2597: 
 2598: =head1 User Name Functions
 2599: 
 2600: =over 4
 2601: 
 2602: =item * &plainname($uname,$udom,$first)
 2603: 
 2604: Takes a users logon name and returns it as a string in
 2605: "first middle last generation" form 
 2606: if $first is set to 'lastname' then it returns it as
 2607: 'lastname generation, firstname middlename' if their is a lastname
 2608: 
 2609: =cut
 2610: 
 2611: 
 2612: ###############################################################
 2613: sub plainname {
 2614:     my ($uname,$udom,$first)=@_;
 2615:     return if (!defined($uname) || !defined($udom));
 2616:     my %names=&getnames($uname,$udom);
 2617:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2618: 					  $names{'middlename'},
 2619: 					  $names{'lastname'},
 2620: 					  $names{'generation'},$first);
 2621:     $name=~s/^\s+//;
 2622:     $name=~s/\s+$//;
 2623:     $name=~s/\s+/ /g;
 2624:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2625:     return $name;
 2626: }
 2627: 
 2628: # -------------------------------------------------------------------- Nickname
 2629: =pod
 2630: 
 2631: =item * &nickname($uname,$udom)
 2632: 
 2633: Gets a users name and returns it as a string as
 2634: 
 2635: "&quot;nickname&quot;"
 2636: 
 2637: if the user has a nickname or
 2638: 
 2639: "first middle last generation"
 2640: 
 2641: if the user does not
 2642: 
 2643: =cut
 2644: 
 2645: sub nickname {
 2646:     my ($uname,$udom)=@_;
 2647:     return if (!defined($uname) || !defined($udom));
 2648:     my %names=&getnames($uname,$udom);
 2649:     my $name=$names{'nickname'};
 2650:     if ($name) {
 2651:        $name='&quot;'.$name.'&quot;'; 
 2652:     } else {
 2653:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2654: 	     $names{'lastname'}.' '.$names{'generation'};
 2655:        $name=~s/\s+$//;
 2656:        $name=~s/\s+/ /g;
 2657:     }
 2658:     return $name;
 2659: }
 2660: 
 2661: sub getnames {
 2662:     my ($uname,$udom)=@_;
 2663:     return if (!defined($uname) || !defined($udom));
 2664:     if ($udom eq 'public' && $uname eq 'public') {
 2665: 	return ('lastname' => &mt('Public'));
 2666:     }
 2667:     my $id=$uname.':'.$udom;
 2668:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2669:     if ($cached) {
 2670: 	return %{$names};
 2671:     } else {
 2672: 	my %loadnames=&Apache::lonnet::get('environment',
 2673:                     ['firstname','middlename','lastname','generation','nickname'],
 2674: 					 $udom,$uname);
 2675: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2676: 	return %loadnames;
 2677:     }
 2678: }
 2679: 
 2680: # -------------------------------------------------------------------- getemails
 2681: 
 2682: =pod
 2683: 
 2684: =item * &getemails($uname,$udom)
 2685: 
 2686: Gets a user's email information and returns it as a hash with keys:
 2687: notification, critnotification, permanentemail
 2688: 
 2689: For notification and critnotification, values are comma-separated lists 
 2690: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2691:  
 2692: 
 2693: =cut
 2694: 
 2695: 
 2696: sub getemails {
 2697:     my ($uname,$udom)=@_;
 2698:     if ($udom eq 'public' && $uname eq 'public') {
 2699: 	return;
 2700:     }
 2701:     if (!$udom) { $udom=$env{'user.domain'}; }
 2702:     if (!$uname) { $uname=$env{'user.name'}; }
 2703:     my $id=$uname.':'.$udom;
 2704:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2705:     if ($cached) {
 2706: 	return %{$names};
 2707:     } else {
 2708: 	my %loadnames=&Apache::lonnet::get('environment',
 2709:                     			   ['notification','critnotification',
 2710: 					    'permanentemail'],
 2711: 					   $udom,$uname);
 2712: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2713: 	return %loadnames;
 2714:     }
 2715: }
 2716: 
 2717: sub flush_email_cache {
 2718:     my ($uname,$udom)=@_;
 2719:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2720:     if (!$uname) { $uname=$env{'user.name'};   }
 2721:     return if ($udom eq 'public' && $uname eq 'public');
 2722:     my $id=$uname.':'.$udom;
 2723:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2724: }
 2725: 
 2726: # -------------------------------------------------------------------- getlangs
 2727: 
 2728: =pod
 2729: 
 2730: =item * &getlangs($uname,$udom)
 2731: 
 2732: Gets a user's language preference and returns it as a hash with key:
 2733: language.
 2734: 
 2735: =cut
 2736: 
 2737: 
 2738: sub getlangs {
 2739:     my ($uname,$udom) = @_;
 2740:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2741:     if (!$uname) { $uname=$env{'user.name'};   }
 2742:     my $id=$uname.':'.$udom;
 2743:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2744:     if ($cached) {
 2745:         return %{$langs};
 2746:     } else {
 2747:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2748:                                            $udom,$uname);
 2749:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2750:         return %loadlangs;
 2751:     }
 2752: }
 2753: 
 2754: sub flush_langs_cache {
 2755:     my ($uname,$udom)=@_;
 2756:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2757:     if (!$uname) { $uname=$env{'user.name'};   }
 2758:     return if ($udom eq 'public' && $uname eq 'public');
 2759:     my $id=$uname.':'.$udom;
 2760:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2761: }
 2762: 
 2763: # ------------------------------------------------------------------ Screenname
 2764: 
 2765: =pod
 2766: 
 2767: =item * &screenname($uname,$udom)
 2768: 
 2769: Gets a users screenname and returns it as a string
 2770: 
 2771: =cut
 2772: 
 2773: sub screenname {
 2774:     my ($uname,$udom)=@_;
 2775:     if ($uname eq $env{'user.name'} &&
 2776: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2777:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2778:     return $names{'screenname'};
 2779: }
 2780: 
 2781: 
 2782: # ------------------------------------------------------------- Message Wrapper
 2783: 
 2784: sub messagewrapper {
 2785:     my ($link,$username,$domain,$subject,$text)=@_;
 2786:     return 
 2787:         '<a href="/adm/email?compose=individual&amp;'.
 2788:         'recname='.$username.'&amp;recdom='.$domain.
 2789: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2790:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2791: }
 2792: # --------------------------------------------------------------- Notes Wrapper
 2793: 
 2794: sub noteswrapper {
 2795:     my ($link,$un,$do)=@_;
 2796:     return 
 2797: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2798: }
 2799: # ------------------------------------------------------------- Aboutme Wrapper
 2800: 
 2801: sub aboutmewrapper {
 2802:     my ($link,$username,$domain,$target)=@_;
 2803:     if (!defined($username)  && !defined($domain)) {
 2804:         return;
 2805:     }
 2806:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2807: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2808: }
 2809: 
 2810: # ------------------------------------------------------------ Syllabus Wrapper
 2811: 
 2812: 
 2813: sub syllabuswrapper {
 2814:     my ($linktext,$coursedir,$domain)=@_;
 2815:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2816: }
 2817: 
 2818: sub track_student_link {
 2819:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2820:     my $link ="/adm/trackstudent?";
 2821:     my $title = 'View recent activity';
 2822:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2823:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2824:         $link .= "selected_student=$sname:$sdom";
 2825:         $title .= ' of this student';
 2826:     } 
 2827:     if (defined($target) && $target !~ /^\s*$/) {
 2828:         $target = qq{target="$target"};
 2829:     } else {
 2830:         $target = '';
 2831:     }
 2832:     if ($start) { $link.='&amp;start='.$start; }
 2833:     $title = &mt($title);
 2834:     $linktext = &mt($linktext);
 2835:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2836: 	&help_open_topic('View_recent_activity');
 2837: }
 2838: 
 2839: # ===================================================== Display a student photo
 2840: 
 2841: 
 2842: sub student_image_tag {
 2843:     my ($domain,$user)=@_;
 2844:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2845:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2846: 	return '<img src="'.$imgsrc.'" align="right" />';
 2847:     } else {
 2848: 	return '';
 2849:     }
 2850: }
 2851: 
 2852: =pod
 2853: 
 2854: =back
 2855: 
 2856: =head1 Access .tab File Data
 2857: 
 2858: =over 4
 2859: 
 2860: =item * &languageids() 
 2861: 
 2862: returns list of all language ids
 2863: 
 2864: =cut
 2865: 
 2866: sub languageids {
 2867:     return sort(keys(%language));
 2868: }
 2869: 
 2870: =pod
 2871: 
 2872: =item * &languagedescription() 
 2873: 
 2874: returns description of a specified language id
 2875: 
 2876: =cut
 2877: 
 2878: sub languagedescription {
 2879:     my $code=shift;
 2880:     return  ($supported_language{$code}?'* ':'').
 2881:             $language{$code}.
 2882: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2883: }
 2884: 
 2885: sub plainlanguagedescription {
 2886:     my $code=shift;
 2887:     return $language{$code};
 2888: }
 2889: 
 2890: sub supportedlanguagecode {
 2891:     my $code=shift;
 2892:     return $supported_language{$code};
 2893: }
 2894: 
 2895: =pod
 2896: 
 2897: =item * &copyrightids() 
 2898: 
 2899: returns list of all copyrights
 2900: 
 2901: =cut
 2902: 
 2903: sub copyrightids {
 2904:     return sort(keys(%cprtag));
 2905: }
 2906: 
 2907: =pod
 2908: 
 2909: =item * &copyrightdescription() 
 2910: 
 2911: returns description of a specified copyright id
 2912: 
 2913: =cut
 2914: 
 2915: sub copyrightdescription {
 2916:     return &mt($cprtag{shift(@_)});
 2917: }
 2918: 
 2919: =pod
 2920: 
 2921: =item * &source_copyrightids() 
 2922: 
 2923: returns list of all source copyrights
 2924: 
 2925: =cut
 2926: 
 2927: sub source_copyrightids {
 2928:     return sort(keys(%scprtag));
 2929: }
 2930: 
 2931: =pod
 2932: 
 2933: =item * &source_copyrightdescription() 
 2934: 
 2935: returns description of a specified source copyright id
 2936: 
 2937: =cut
 2938: 
 2939: sub source_copyrightdescription {
 2940:     return &mt($scprtag{shift(@_)});
 2941: }
 2942: 
 2943: =pod
 2944: 
 2945: =item * &filecategories() 
 2946: 
 2947: returns list of all file categories
 2948: 
 2949: =cut
 2950: 
 2951: sub filecategories {
 2952:     return sort(keys(%category_extensions));
 2953: }
 2954: 
 2955: =pod
 2956: 
 2957: =item * &filecategorytypes() 
 2958: 
 2959: returns list of file types belonging to a given file
 2960: category
 2961: 
 2962: =cut
 2963: 
 2964: sub filecategorytypes {
 2965:     my ($cat) = @_;
 2966:     return @{$category_extensions{lc($cat)}};
 2967: }
 2968: 
 2969: =pod
 2970: 
 2971: =item * &fileembstyle() 
 2972: 
 2973: returns embedding style for a specified file type
 2974: 
 2975: =cut
 2976: 
 2977: sub fileembstyle {
 2978:     return $fe{lc(shift(@_))};
 2979: }
 2980: 
 2981: sub filemimetype {
 2982:     return $fm{lc(shift(@_))};
 2983: }
 2984: 
 2985: 
 2986: sub filecategoryselect {
 2987:     my ($name,$value)=@_;
 2988:     return &select_form($value,$name,
 2989: 			'' => &mt('Any category'),
 2990: 			map { $_,$_ } sort(keys(%category_extensions)));
 2991: }
 2992: 
 2993: =pod
 2994: 
 2995: =item * &filedescription() 
 2996: 
 2997: returns description for a specified file type
 2998: 
 2999: =cut
 3000: 
 3001: sub filedescription {
 3002:     my $file_description = $fd{lc(shift())};
 3003:     $file_description =~ s:([\[\]]):~$1:g;
 3004:     return &mt($file_description);
 3005: }
 3006: 
 3007: =pod
 3008: 
 3009: =item * &filedescriptionex() 
 3010: 
 3011: returns description for a specified file type with
 3012: extra formatting
 3013: 
 3014: =cut
 3015: 
 3016: sub filedescriptionex {
 3017:     my $ex=shift;
 3018:     my $file_description = $fd{lc($ex)};
 3019:     $file_description =~ s:([\[\]]):~$1:g;
 3020:     return '.'.$ex.' '.&mt($file_description);
 3021: }
 3022: 
 3023: # End of .tab access
 3024: =pod
 3025: 
 3026: =back
 3027: 
 3028: =cut
 3029: 
 3030: # ------------------------------------------------------------------ File Types
 3031: sub fileextensions {
 3032:     return sort(keys(%fe));
 3033: }
 3034: 
 3035: # ----------------------------------------------------------- Display Languages
 3036: # returns a hash with all desired display languages
 3037: #
 3038: 
 3039: sub display_languages {
 3040:     my %languages=();
 3041:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3042: 	$languages{$lang}=1;
 3043:     }
 3044:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3045:     if ($env{'form.displaylanguage'}) {
 3046: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3047: 	    $languages{$lang}=1;
 3048:         }
 3049:     }
 3050:     return %languages;
 3051: }
 3052: 
 3053: sub languages {
 3054:     my ($possible_langs) = @_;
 3055:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3056:     if (!ref($possible_langs)) {
 3057: 	if( wantarray ) {
 3058: 	    return @preferred_langs;
 3059: 	} else {
 3060: 	    return $preferred_langs[0];
 3061: 	}
 3062:     }
 3063:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3064:     my @preferred_possibilities;
 3065:     foreach my $preferred_lang (@preferred_langs) {
 3066: 	if (exists($possibilities{$preferred_lang})) {
 3067: 	    push(@preferred_possibilities, $preferred_lang);
 3068: 	}
 3069:     }
 3070:     if( wantarray ) {
 3071: 	return @preferred_possibilities;
 3072:     }
 3073:     return $preferred_possibilities[0];
 3074: }
 3075: 
 3076: ###############################################################
 3077: ##               Student Answer Attempts                     ##
 3078: ###############################################################
 3079: 
 3080: =pod
 3081: 
 3082: =head1 Alternate Problem Views
 3083: 
 3084: =over 4
 3085: 
 3086: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3087:     $getattempt, $regexp, $gradesub)
 3088: 
 3089: Return string with previous attempt on problem. Arguments:
 3090: 
 3091: =over 4
 3092: 
 3093: =item * $symb: Problem, including path
 3094: 
 3095: =item * $username: username of the desired student
 3096: 
 3097: =item * $domain: domain of the desired student
 3098: 
 3099: =item * $course: Course ID
 3100: 
 3101: =item * $getattempt: Leave blank for all attempts, otherwise put
 3102:     something
 3103: 
 3104: =item * $regexp: if string matches this regexp, the string will be
 3105:     sent to $gradesub
 3106: 
 3107: =item * $gradesub: routine that processes the string if it matches $regexp
 3108: 
 3109: =back
 3110: 
 3111: The output string is a table containing all desired attempts, if any.
 3112: 
 3113: =cut
 3114: 
 3115: sub get_previous_attempt {
 3116:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3117:   my $prevattempts='';
 3118:   no strict 'refs';
 3119:   if ($symb) {
 3120:     my (%returnhash)=
 3121:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3122:     if ($returnhash{'version'}) {
 3123:       my %lasthash=();
 3124:       my $version;
 3125:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3126:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3127: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3128:         }
 3129:       }
 3130:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3131:       $prevattempts.='<th>'.&mt('History').'</th>';
 3132:       foreach my $key (sort(keys(%lasthash))) {
 3133: 	my ($ign,@parts) = split(/\./,$key);
 3134: 	if ($#parts > 0) {
 3135: 	  my $data=$parts[-1];
 3136: 	  pop(@parts);
 3137: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3138: 	} else {
 3139: 	  if ($#parts == 0) {
 3140: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3141: 	  } else {
 3142: 	    $prevattempts.='<th>'.$ign.'</th>';
 3143: 	  }
 3144: 	}
 3145:       }
 3146:       $prevattempts.=&end_data_table_header_row();
 3147:       if ($getattempt eq '') {
 3148: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3149: 	  $prevattempts.=&start_data_table_row().
 3150: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3151: 	    foreach my $key (sort(keys(%lasthash))) {
 3152: 		my $value = &format_previous_attempt_value($key,
 3153: 							   $returnhash{$version.':'.$key});
 3154: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3155: 	    }
 3156: 	  $prevattempts.=&end_data_table_row();
 3157: 	 }
 3158:       }
 3159:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3160:       foreach my $key (sort(keys(%lasthash))) {
 3161: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3162: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3163: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3164:       }
 3165:       $prevattempts.= &end_data_table_row().&end_data_table();
 3166:     } else {
 3167:       $prevattempts=
 3168: 	  &start_data_table().&start_data_table_row().
 3169: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3170: 	  &end_data_table_row().&end_data_table();
 3171:     }
 3172:   } else {
 3173:     $prevattempts=
 3174: 	  &start_data_table().&start_data_table_row().
 3175: 	  '<td>'.&mt('No data.').'</td>'.
 3176: 	  &end_data_table_row().&end_data_table();
 3177:   }
 3178: }
 3179: 
 3180: sub format_previous_attempt_value {
 3181:     my ($key,$value) = @_;
 3182:     if ($key =~ /timestamp/) {
 3183: 	$value = &Apache::lonlocal::locallocaltime($value);
 3184:     } elsif (ref($value) eq 'ARRAY') {
 3185: 	$value = '('.join(', ', @{ $value }).')';
 3186:     } else {
 3187: 	$value = &unescape($value);
 3188:     }
 3189:     return $value;
 3190: }
 3191: 
 3192: 
 3193: sub relative_to_absolute {
 3194:     my ($url,$output)=@_;
 3195:     my $parser=HTML::TokeParser->new(\$output);
 3196:     my $token;
 3197:     my $thisdir=$url;
 3198:     my @rlinks=();
 3199:     while ($token=$parser->get_token) {
 3200: 	if ($token->[0] eq 'S') {
 3201: 	    if ($token->[1] eq 'a') {
 3202: 		if ($token->[2]->{'href'}) {
 3203: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3204: 		}
 3205: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3206: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3207: 	    } elsif ($token->[1] eq 'base') {
 3208: 		$thisdir=$token->[2]->{'href'};
 3209: 	    }
 3210: 	}
 3211:     }
 3212:     $thisdir=~s-/[^/]*$--;
 3213:     foreach my $link (@rlinks) {
 3214: 	unless (($link=~/^https?\:\/\//i) ||
 3215: 		($link=~/^\//) ||
 3216: 		($link=~/^javascript:/i) ||
 3217: 		($link=~/^mailto:/i) ||
 3218: 		($link=~/^\#/)) {
 3219: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3220: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3221: 	}
 3222:     }
 3223: # -------------------------------------------------- Deal with Applet codebases
 3224:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3225:     return $output;
 3226: }
 3227: 
 3228: =pod
 3229: 
 3230: =item * &get_student_view()
 3231: 
 3232: show a snapshot of what student was looking at
 3233: 
 3234: =cut
 3235: 
 3236: sub get_student_view {
 3237:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3238:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3239:   my (%form);
 3240:   my @elements=('symb','courseid','domain','username');
 3241:   foreach my $element (@elements) {
 3242:       $form{'grade_'.$element}=eval '$'.$element #'
 3243:   }
 3244:   if (defined($moreenv)) {
 3245:       %form=(%form,%{$moreenv});
 3246:   }
 3247:   if (defined($target)) { $form{'grade_target'} = $target; }
 3248:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3249:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3250:   $userview=~s/\<body[^\>]*\>//gi;
 3251:   $userview=~s/\<\/body\>//gi;
 3252:   $userview=~s/\<html\>//gi;
 3253:   $userview=~s/\<\/html\>//gi;
 3254:   $userview=~s/\<head\>//gi;
 3255:   $userview=~s/\<\/head\>//gi;
 3256:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3257:   $userview=&relative_to_absolute($feedurl,$userview);
 3258:   if (wantarray) {
 3259:      return ($userview,$response);
 3260:   } else {
 3261:      return $userview;
 3262:   }
 3263: }
 3264: 
 3265: sub get_student_view_with_retries {
 3266:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3267: 
 3268:     my $ok = 0;                 # True if we got a good response.
 3269:     my $content;
 3270:     my $response;
 3271: 
 3272:     # Try to get the student_view done. within the retries count:
 3273:     
 3274:     do {
 3275:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3276:          $ok      = $response->is_success;
 3277:          if (!$ok) {
 3278:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3279:          }
 3280:          $retries--;
 3281:     } while (!$ok && ($retries > 0));
 3282:     
 3283:     if (!$ok) {
 3284:        $content = '';          # On error return an empty content.
 3285:     }
 3286:     if (wantarray) {
 3287:        return ($content, $response);
 3288:     } else {
 3289:        return $content;
 3290:     }
 3291: }
 3292: 
 3293: =pod
 3294: 
 3295: =item * &get_student_answers() 
 3296: 
 3297: show a snapshot of how student was answering problem
 3298: 
 3299: =cut
 3300: 
 3301: sub get_student_answers {
 3302:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3303:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3304:   my (%moreenv);
 3305:   my @elements=('symb','courseid','domain','username');
 3306:   foreach my $element (@elements) {
 3307:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3308:   }
 3309:   $moreenv{'grade_target'}='answer';
 3310:   %moreenv=(%form,%moreenv);
 3311:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3312:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3313:   return $userview;
 3314: }
 3315: 
 3316: =pod
 3317: 
 3318: =item * &submlink()
 3319: 
 3320: Inputs: $text $uname $udom $symb $target
 3321: 
 3322: Returns: A link to grades.pm such as to see the SUBM view of a student
 3323: 
 3324: =cut
 3325: 
 3326: ###############################################
 3327: sub submlink {
 3328:     my ($text,$uname,$udom,$symb,$target)=@_;
 3329:     if (!($uname && $udom)) {
 3330: 	(my $cursymb, my $courseid,$udom,$uname)=
 3331: 	    &Apache::lonnet::whichuser($symb);
 3332: 	if (!$symb) { $symb=$cursymb; }
 3333:     }
 3334:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3335:     $symb=&escape($symb);
 3336:     if ($target) { $target="target=\"$target\""; }
 3337:     return '<a href="/adm/grades?&command=submission&'.
 3338: 	'symb='.$symb.'&student='.$uname.
 3339: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3340: }
 3341: ##############################################
 3342: 
 3343: =pod
 3344: 
 3345: =item * &pgrdlink()
 3346: 
 3347: Inputs: $text $uname $udom $symb $target
 3348: 
 3349: Returns: A link to grades.pm such as to see the PGRD view of a student
 3350: 
 3351: =cut
 3352: 
 3353: ###############################################
 3354: sub pgrdlink {
 3355:     my $link=&submlink(@_);
 3356:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3357:     return $link;
 3358: }
 3359: ##############################################
 3360: 
 3361: =pod
 3362: 
 3363: =item * &pprmlink()
 3364: 
 3365: Inputs: $text $uname $udom $symb $target
 3366: 
 3367: Returns: A link to parmset.pm such as to see the PPRM view of a
 3368: student and a specific resource
 3369: 
 3370: =cut
 3371: 
 3372: ###############################################
 3373: sub pprmlink {
 3374:     my ($text,$uname,$udom,$symb,$target)=@_;
 3375:     if (!($uname && $udom)) {
 3376: 	(my $cursymb, my $courseid,$udom,$uname)=
 3377: 	    &Apache::lonnet::whichuser($symb);
 3378: 	if (!$symb) { $symb=$cursymb; }
 3379:     }
 3380:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3381:     $symb=&escape($symb);
 3382:     if ($target) { $target="target=\"$target\""; }
 3383:     return '<a href="/adm/parmset?command=set&amp;'.
 3384: 	'symb='.$symb.'&amp;uname='.$uname.
 3385: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3386: }
 3387: ##############################################
 3388: 
 3389: =pod
 3390: 
 3391: =back
 3392: 
 3393: =cut
 3394: 
 3395: ###############################################
 3396: 
 3397: 
 3398: sub timehash {
 3399:     my ($thistime) = @_;
 3400:     my $timezone = &Apache::lonlocal::gettimezone();
 3401:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3402:                      ->set_time_zone($timezone);
 3403:     my $wday = $dt->day_of_week();
 3404:     if ($wday == 7) { $wday = 0; }
 3405:     return ( 'second' => $dt->second(),
 3406:              'minute' => $dt->minute(),
 3407:              'hour'   => $dt->hour(),
 3408:              'day'     => $dt->day_of_month(),
 3409:              'month'   => $dt->month(),
 3410:              'year'    => $dt->year(),
 3411:              'weekday' => $wday,
 3412:              'dayyear' => $dt->day_of_year(),
 3413:              'dlsav'   => $dt->is_dst() );
 3414: }
 3415: 
 3416: sub utc_string {
 3417:     my ($date)=@_;
 3418:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3419: }
 3420: 
 3421: sub maketime {
 3422:     my %th=@_;
 3423:     my ($epoch_time,$timezone,$dt);
 3424:     $timezone = &Apache::lonlocal::gettimezone();
 3425:     eval {
 3426:         $dt = DateTime->new( year   => $th{'year'},
 3427:                              month  => $th{'month'},
 3428:                              day    => $th{'day'},
 3429:                              hour   => $th{'hour'},
 3430:                              minute => $th{'minute'},
 3431:                              second => $th{'second'},
 3432:                              time_zone => $timezone,
 3433:                          );
 3434:     };
 3435:     if (!$@) {
 3436:         $epoch_time = $dt->epoch;
 3437:         if ($epoch_time) {
 3438:             return $epoch_time;
 3439:         }
 3440:     }
 3441:     return POSIX::mktime(
 3442:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3443:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3444: }
 3445: 
 3446: #########################################
 3447: 
 3448: sub findallcourses {
 3449:     my ($roles,$uname,$udom) = @_;
 3450:     my %roles;
 3451:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3452:     my %courses;
 3453:     my $now=time;
 3454:     if (!defined($uname)) {
 3455:         $uname = $env{'user.name'};
 3456:     }
 3457:     if (!defined($udom)) {
 3458:         $udom = $env{'user.domain'};
 3459:     }
 3460:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3461:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3462:         if (!%roles) {
 3463:             %roles = (
 3464:                        cc => 1,
 3465:                        in => 1,
 3466:                        ep => 1,
 3467:                        ta => 1,
 3468:                        cr => 1,
 3469:                        st => 1,
 3470:              );
 3471:         }
 3472:         foreach my $entry (keys(%roleshash)) {
 3473:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3474:             if ($trole =~ /^cr/) { 
 3475:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3476:             } else {
 3477:                 next if (!exists($roles{$trole}));
 3478:             }
 3479:             if ($tend) {
 3480:                 next if ($tend < $now);
 3481:             }
 3482:             if ($tstart) {
 3483:                 next if ($tstart > $now);
 3484:             }
 3485:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3486:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3487:             if ($secpart eq '') {
 3488:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3489:                 $sec = 'none';
 3490:                 $realsec = '';
 3491:             } else {
 3492:                 $cnum = $cnumpart;
 3493:                 ($sec,$role) = split(/_/,$secpart);
 3494:                 $realsec = $sec;
 3495:             }
 3496:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3497:         }
 3498:     } else {
 3499:         foreach my $key (keys(%env)) {
 3500: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3501:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3502: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3503: 	        next if ($role eq 'ca' || $role eq 'aa');
 3504: 	        next if (%roles && !exists($roles{$role}));
 3505: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3506:                 my $active=1;
 3507:                 if ($starttime) {
 3508: 		    if ($now<$starttime) { $active=0; }
 3509:                 }
 3510:                 if ($endtime) {
 3511:                     if ($now>$endtime) { $active=0; }
 3512:                 }
 3513:                 if ($active) {
 3514:                     if ($sec eq '') {
 3515:                         $sec = 'none';
 3516:                     }
 3517:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3518:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3519:                 }
 3520:             }
 3521:         }
 3522:     }
 3523:     return %courses;
 3524: }
 3525: 
 3526: ###############################################
 3527: 
 3528: sub blockcheck {
 3529:     my ($setters,$activity,$uname,$udom) = @_;
 3530: 
 3531:     if (!defined($udom)) {
 3532:         $udom = $env{'user.domain'};
 3533:     }
 3534:     if (!defined($uname)) {
 3535:         $uname = $env{'user.name'};
 3536:     }
 3537: 
 3538:     # If uname and udom are for a course, check for blocks in the course.
 3539: 
 3540:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3541:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3542:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3543:         return ($startblock,$endblock);
 3544:     }
 3545: 
 3546:     my $startblock = 0;
 3547:     my $endblock = 0;
 3548:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3549: 
 3550:     # If uname is for a user, and activity is course-specific, i.e.,
 3551:     # boards, chat or groups, check for blocking in current course only.
 3552: 
 3553:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3554:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3555:         foreach my $key (keys(%live_courses)) {
 3556:             if ($key ne $env{'request.course.id'}) {
 3557:                 delete($live_courses{$key});
 3558:             }
 3559:         }
 3560:     }
 3561: 
 3562:     my $otheruser = 0;
 3563:     my %own_courses;
 3564:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3565:         # Resource belongs to user other than current user.
 3566:         $otheruser = 1;
 3567:         # Gather courses for current user
 3568:         %own_courses = 
 3569:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3570:     }
 3571: 
 3572:     # Gather active course roles - course coordinator, instructor, 
 3573:     # exam proctor, ta, student, or custom role.
 3574: 
 3575:     foreach my $course (keys(%live_courses)) {
 3576:         my ($cdom,$cnum);
 3577:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3578:             $cdom = $env{'course.'.$course.'.domain'};
 3579:             $cnum = $env{'course.'.$course.'.num'};
 3580:         } else {
 3581:             ($cdom,$cnum) = split(/_/,$course); 
 3582:         }
 3583:         my $no_ownblock = 0;
 3584:         my $no_userblock = 0;
 3585:         if ($otheruser && $activity ne 'com') {
 3586:             # Check if current user has 'evb' priv for this
 3587:             if (defined($own_courses{$course})) {
 3588:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3589:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3590:                     if ($sec ne 'none') {
 3591:                         $checkrole .= '/'.$sec;
 3592:                     }
 3593:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3594:                         $no_ownblock = 1;
 3595:                         last;
 3596:                     }
 3597:                 }
 3598:             }
 3599:             # if they have 'evb' priv and are currently not playing student
 3600:             next if (($no_ownblock) &&
 3601:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3602:         }
 3603:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3604:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3605:             if ($sec ne 'none') {
 3606:                 $checkrole .= '/'.$sec;
 3607:             }
 3608:             if ($otheruser) {
 3609:                 # Resource belongs to user other than current user.
 3610:                 # Assemble privs for that user, and check for 'evb' priv.
 3611:                 my ($trole,$tdom,$tnum,$tsec);
 3612:                 my $entry = $live_courses{$course}{$sec};
 3613:                 if ($entry =~ /^cr/) {
 3614:                     ($trole,$tdom,$tnum,$tsec) = 
 3615:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3616:                 } else {
 3617:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3618:                 }
 3619:                 my ($spec,$area,$trest,%allroles,%userroles);
 3620:                 $area = '/'.$tdom.'/'.$tnum;
 3621:                 $trest = $tnum;
 3622:                 if ($tsec ne '') {
 3623:                     $area .= '/'.$tsec;
 3624:                     $trest .= '/'.$tsec;
 3625:                 }
 3626:                 $spec = $trole.'.'.$area;
 3627:                 if ($trole =~ /^cr/) {
 3628:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3629:                                                       $tdom,$spec,$trest,$area);
 3630:                 } else {
 3631:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3632:                                                        $tdom,$spec,$trest,$area);
 3633:                 }
 3634:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3635:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3636:                     if ($1) {
 3637:                         $no_userblock = 1;
 3638:                         last;
 3639:                     }
 3640:                 }
 3641:             } else {
 3642:                 # Resource belongs to current user
 3643:                 # Check for 'evb' priv via lonnet::allowed().
 3644:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3645:                     $no_ownblock = 1;
 3646:                     last;
 3647:                 }
 3648:             }
 3649:         }
 3650:         # if they have the evb priv and are currently not playing student
 3651:         next if (($no_ownblock) &&
 3652:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3653:         next if ($no_userblock);
 3654: 
 3655:         # Retrieve blocking times and identity of blocker for course
 3656:         # of specified user, unless user has 'evb' privilege.
 3657:         
 3658:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3659:         if (($start != 0) && 
 3660:             (($startblock == 0) || ($startblock > $start))) {
 3661:             $startblock = $start;
 3662:         }
 3663:         if (($end != 0)  &&
 3664:             (($endblock == 0) || ($endblock < $end))) {
 3665:             $endblock = $end;
 3666:         }
 3667:     }
 3668:     return ($startblock,$endblock);
 3669: }
 3670: 
 3671: sub get_blocks {
 3672:     my ($setters,$activity,$cdom,$cnum) = @_;
 3673:     my $startblock = 0;
 3674:     my $endblock = 0;
 3675:     my $course = $cdom.'_'.$cnum;
 3676:     $setters->{$course} = {};
 3677:     $setters->{$course}{'staff'} = [];
 3678:     $setters->{$course}{'times'} = [];
 3679:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3680:     foreach my $record (keys(%records)) {
 3681:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3682:         if ($start <= time && $end >= time) {
 3683:             my ($staff_name,$staff_dom,$title,$blocks) =
 3684:                 &parse_block_record($records{$record});
 3685:             if ($blocks->{$activity} eq 'on') {
 3686:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3687:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3688:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3689:                     $startblock = $start;
 3690:                 }
 3691:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3692:                     $endblock = $end;
 3693:                 }
 3694:             }
 3695:         }
 3696:     }
 3697:     return ($startblock,$endblock);
 3698: }
 3699: 
 3700: sub parse_block_record {
 3701:     my ($record) = @_;
 3702:     my ($setuname,$setudom,$title,$blocks);
 3703:     if (ref($record) eq 'HASH') {
 3704:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3705:         $title = &unescape($record->{'event'});
 3706:         $blocks = $record->{'blocks'};
 3707:     } else {
 3708:         my @data = split(/:/,$record,3);
 3709:         if (scalar(@data) eq 2) {
 3710:             $title = $data[1];
 3711:             ($setuname,$setudom) = split(/@/,$data[0]);
 3712:         } else {
 3713:             ($setuname,$setudom,$title) = @data;
 3714:         }
 3715:         $blocks = { 'com' => 'on' };
 3716:     }
 3717:     return ($setuname,$setudom,$title,$blocks);
 3718: }
 3719: 
 3720: sub build_block_table {
 3721:     my ($startblock,$endblock,$setters) = @_;
 3722:     my %lt = &Apache::lonlocal::texthash(
 3723:         'cacb' => 'Currently active communication blocks',
 3724:         'cour' => 'Course',
 3725:         'dura' => 'Duration',
 3726:         'blse' => 'Block set by'
 3727:     );
 3728:     my $output;
 3729:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3730:     $output .= &start_data_table();
 3731:     $output .= '
 3732: <tr>
 3733:  <th>'.$lt{'cour'}.'</th>
 3734:  <th>'.$lt{'dura'}.'</th>
 3735:  <th>'.$lt{'blse'}.'</th>
 3736: </tr>
 3737: ';
 3738:     foreach my $course (keys(%{$setters})) {
 3739:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3740:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3741:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3742:             my $fullname = &plainname($uname,$udom);
 3743:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3744:                 && $env{'user.name'} ne 'public' 
 3745:                 && $env{'user.domain'} ne 'public') {
 3746:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3747:             }
 3748:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3749:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3750:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3751:             $output .= &Apache::loncommon::start_data_table_row().
 3752:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3753:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3754:                        '<td>'.$fullname.'</td>'.
 3755:                         &Apache::loncommon::end_data_table_row();
 3756:         }
 3757:     }
 3758:     $output .= &end_data_table();
 3759: }
 3760: 
 3761: sub blocking_status {
 3762:     my ($activity,$uname,$udom) = @_;
 3763:     my %setters;
 3764:     my ($blocked,$output,$ownitem,$is_course);
 3765:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3766:     if ($startblock && $endblock) {
 3767:         $blocked = 1;
 3768:         if (wantarray) {
 3769:             my $category;
 3770:             if ($activity eq 'boards') {
 3771:                 $category = 'Discussion posts in this course';
 3772:             } elsif ($activity eq 'blogs') {
 3773:                 $category = 'Blogs';
 3774:             } elsif ($activity eq 'port') {
 3775:                 if (defined($uname) && defined($udom)) {
 3776:                     if ($uname eq $env{'user.name'} &&
 3777:                         $udom eq $env{'user.domain'}) {
 3778:                         $ownitem = 1;
 3779:                     }
 3780:                 }
 3781:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3782:                 if ($ownitem) { 
 3783:                     $category = 'Your portfolio files';  
 3784:                 } elsif ($is_course) {
 3785:                     my $coursedesc;
 3786:                     foreach my $course (keys(%setters)) {
 3787:                         my %courseinfo =
 3788:                              &Apache::lonnet::coursedescription($course);
 3789:                         $coursedesc = $courseinfo{'description'};
 3790:                     }
 3791:                     $category = "Group files in the course '$coursedesc'";
 3792:                 } else {
 3793:                     $category = 'Portfolio files belonging to ';
 3794:                     if ($env{'user.name'} eq 'public' && 
 3795:                         $env{'user.domain'} eq 'public') {
 3796:                         $category .= &plainname($uname,$udom);
 3797:                     } else {
 3798:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3799:                     }
 3800:                 }
 3801:             } elsif ($activity eq 'groups') {
 3802:                 $category = 'Groups in this course';
 3803:             }
 3804:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3805:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3806:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3807:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3808:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3809:             }
 3810:         }
 3811:     }
 3812:     if (wantarray) {
 3813:         return ($blocked,$output);
 3814:     } else {
 3815:         return $blocked;
 3816:     }
 3817: }
 3818: 
 3819: ###############################################
 3820: 
 3821: sub check_ip_acc {
 3822:     my ($acc)=@_;
 3823:     &Apache::lonxml::debug("acc is $acc");
 3824:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3825:         return 1;
 3826:     }
 3827:     my $allowed=0;
 3828:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3829: 
 3830:     my $name;
 3831:     foreach my $pattern (split(',',$acc)) {
 3832:         $pattern =~ s/^\s*//;
 3833:         $pattern =~ s/\s*$//;
 3834:         if ($pattern =~ /\*$/) {
 3835:             #35.8.*
 3836:             $pattern=~s/\*//;
 3837:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3838:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3839:             #35.8.3.[34-56]
 3840:             my $low=$2;
 3841:             my $high=$3;
 3842:             $pattern=$1;
 3843:             if ($ip =~ /^\Q$pattern\E/) {
 3844:                 my $last=(split(/\./,$ip))[3];
 3845:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3846:             }
 3847:         } elsif ($pattern =~ /^\*/) {
 3848:             #*.msu.edu
 3849:             $pattern=~s/\*//;
 3850:             if (!defined($name)) {
 3851:                 use Socket;
 3852:                 my $netaddr=inet_aton($ip);
 3853:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3854:             }
 3855:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3856:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3857:             #127.0.0.1
 3858:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3859:         } else {
 3860:             #some.name.com
 3861:             if (!defined($name)) {
 3862:                 use Socket;
 3863:                 my $netaddr=inet_aton($ip);
 3864:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3865:             }
 3866:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3867:         }
 3868:         if ($allowed) { last; }
 3869:     }
 3870:     return $allowed;
 3871: }
 3872: 
 3873: ###############################################
 3874: 
 3875: =pod
 3876: 
 3877: =head1 Domain Template Functions
 3878: 
 3879: =over 4
 3880: 
 3881: =item * &determinedomain()
 3882: 
 3883: Inputs: $domain (usually will be undef)
 3884: 
 3885: Returns: Determines which domain should be used for designs
 3886: 
 3887: =cut
 3888: 
 3889: ###############################################
 3890: sub determinedomain {
 3891:     my $domain=shift;
 3892:     if (! $domain) {
 3893:         # Determine domain if we have not been given one
 3894:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3895:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3896:         if ($env{'request.role.domain'}) { 
 3897:             $domain=$env{'request.role.domain'}; 
 3898:         }
 3899:     }
 3900:     return $domain;
 3901: }
 3902: ###############################################
 3903: 
 3904: sub devalidate_domconfig_cache {
 3905:     my ($udom)=@_;
 3906:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3907: }
 3908: 
 3909: # ---------------------- Get domain configuration for a domain
 3910: sub get_domainconf {
 3911:     my ($udom) = @_;
 3912:     my $cachetime=1800;
 3913:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3914:     if (defined($cached)) { return %{$result}; }
 3915: 
 3916:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3917: 					     ['login','rolecolors'],$udom);
 3918:     my (%designhash,%legacy);
 3919:     if (keys(%domconfig) > 0) {
 3920:         if (ref($domconfig{'login'}) eq 'HASH') {
 3921:             if (keys(%{$domconfig{'login'}})) {
 3922:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3923:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3924:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3925:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 3926:                                 $domconfig{'login'}{$key}{$img};
 3927:                         }
 3928:                     } else {
 3929:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3930:                     }
 3931:                 }
 3932:             } else {
 3933:                 $legacy{'login'} = 1;
 3934:             }
 3935:         } else {
 3936:             $legacy{'login'} = 1;
 3937:         }
 3938:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3939:             if (keys(%{$domconfig{'rolecolors'}})) {
 3940:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3941:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3942:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3943:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3944:                         }
 3945:                     }
 3946:                 }
 3947:             } else {
 3948:                 $legacy{'rolecolors'} = 1;
 3949:             }
 3950:         } else {
 3951:             $legacy{'rolecolors'} = 1;
 3952:         }
 3953:         if (keys(%legacy) > 0) {
 3954:             my %legacyhash = &get_legacy_domconf($udom);
 3955:             foreach my $item (keys(%legacyhash)) {
 3956:                 if ($item =~ /^\Q$udom\E\.login/) {
 3957:                     if ($legacy{'login'}) { 
 3958:                         $designhash{$item} = $legacyhash{$item};
 3959:                     }
 3960:                 } else {
 3961:                     if ($legacy{'rolecolors'}) {
 3962:                         $designhash{$item} = $legacyhash{$item};
 3963:                     }
 3964:                 }
 3965:             }
 3966:         }
 3967:     } else {
 3968:         %designhash = &get_legacy_domconf($udom); 
 3969:     }
 3970:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 3971: 				  $cachetime);
 3972:     return %designhash;
 3973: }
 3974: 
 3975: sub get_legacy_domconf {
 3976:     my ($udom) = @_;
 3977:     my %legacyhash;
 3978:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 3979:     my $designfile =  $designdir.'/'.$udom.'.tab';
 3980:     if (-e $designfile) {
 3981:         if ( open (my $fh,"<$designfile") ) {
 3982:             while (my $line = <$fh>) {
 3983:                 next if ($line =~ /^\#/);
 3984:                 chomp($line);
 3985:                 my ($key,$val)=(split(/\=/,$line));
 3986:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 3987:             }
 3988:             close($fh);
 3989:         }
 3990:     }
 3991:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 3992:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 3993:     }
 3994:     return %legacyhash;
 3995: }
 3996: 
 3997: =pod
 3998: 
 3999: =item * &domainlogo()
 4000: 
 4001: Inputs: $domain (usually will be undef)
 4002: 
 4003: Returns: A link to a domain logo, if the domain logo exists.
 4004: If the domain logo does not exist, a description of the domain.
 4005: 
 4006: =cut
 4007: 
 4008: ###############################################
 4009: sub domainlogo {
 4010:     my $domain = &determinedomain(shift);
 4011:     my %designhash = &get_domainconf($domain);    
 4012:     # See if there is a logo
 4013:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4014:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4015:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4016: 	    if ($imgsrc =~ m{^/res/}) {
 4017: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4018: 		&Apache::lonnet::repcopy($local_name);
 4019: 	    }
 4020: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4021:         } 
 4022:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4023:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4024:         return &Apache::lonnet::domain($domain,'description');
 4025:     } else {
 4026:         return '';
 4027:     }
 4028: }
 4029: ##############################################
 4030: 
 4031: =pod
 4032: 
 4033: =item * &designparm()
 4034: 
 4035: Inputs: $which parameter; $domain (usually will be undef)
 4036: 
 4037: Returns: value of designparamter $which
 4038: 
 4039: =cut
 4040: 
 4041: 
 4042: ##############################################
 4043: sub designparm {
 4044:     my ($which,$domain)=@_;
 4045:     if ($env{'browser.blackwhite'} eq 'on') {
 4046: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4047: 	    return '#000000';
 4048: 	}
 4049: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4050: 	    return '#FFFFFF';
 4051: 	}
 4052: 	if ($which=~/\.tabbg$/) {
 4053: 	    return '#CCCCCC';
 4054: 	}
 4055:     }
 4056:     if (exists($env{'environment.color.'.$which})) {
 4057: 	return $env{'environment.color.'.$which};
 4058:     }
 4059:     $domain=&determinedomain($domain);
 4060:     my %domdesign = &get_domainconf($domain);
 4061:     my $output;
 4062:     if ($domdesign{$domain.'.'.$which} ne '') {
 4063: 	$output = $domdesign{$domain.'.'.$which};
 4064:     } else {
 4065:         $output = $defaultdesign{$which};
 4066:     }
 4067:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4068:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4069:         if ($output =~ m{^/(adm|res)/}) {
 4070: 	    if ($output =~ m{^/res/}) {
 4071: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4072: 		&Apache::lonnet::repcopy($local_name);
 4073: 	    }
 4074:             $output = &lonhttpdurl($output);
 4075:         }
 4076:     }
 4077:     return $output;
 4078: }
 4079: 
 4080: ###############################################
 4081: ###############################################
 4082: 
 4083: =pod
 4084: 
 4085: =back
 4086: 
 4087: =head1 HTML Helpers
 4088: 
 4089: =over 4
 4090: 
 4091: =item * &bodytag()
 4092: 
 4093: Returns a uniform header for LON-CAPA web pages.
 4094: 
 4095: Inputs: 
 4096: 
 4097: =over 4
 4098: 
 4099: =item * $title, A title to be displayed on the page.
 4100: 
 4101: =item * $function, the current role (can be undef).
 4102: 
 4103: =item * $addentries, extra parameters for the <body> tag.
 4104: 
 4105: =item * $bodyonly, if defined, only return the <body> tag.
 4106: 
 4107: =item * $domain, if defined, force a given domain.
 4108: 
 4109: =item * $forcereg, if page should register as content page (relevant for 
 4110:             text interface only)
 4111: 
 4112: =item * $customtitle, alternate text to use instead of $title
 4113:                       in the title box that appears, this text
 4114:                       is not auto translated like the $title is
 4115: 
 4116: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4117:                    navigational links
 4118: 
 4119: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4120: 
 4121: =item * $notitle, if true keep the nav controls, but remove the title bar
 4122: 
 4123: =item * $no_inline_link, if true and in remote mode, don't show the 
 4124:          'Switch To Inline Menu' link
 4125: 
 4126: =item * $args, optional argument valid values are
 4127:             no_auto_mt_title -> prevents &mt()ing the title arg
 4128:             inherit_jsmath -> when creating popup window in a page,
 4129:                               should it have jsmath forced on by the
 4130:                               current page
 4131: 
 4132: =back
 4133: 
 4134: Returns: A uniform header for LON-CAPA web pages.  
 4135: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4136: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4137: other decorations will be returned.
 4138: 
 4139: =cut
 4140: 
 4141: sub bodytag {
 4142:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4143: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4144: 
 4145:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4146: 
 4147:     $function = &get_users_function() if (!$function);
 4148:     my $img =    &designparm($function.'.img',$domain);
 4149:     my $font =   &designparm($function.'.font',$domain);
 4150:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4151: 
 4152:     my %design = ( 'style'   => 'margin-top: 0px',
 4153: 		   'bgcolor' => $pgbg,
 4154: 		   'text'    => $font,
 4155:                    'alink'   => &designparm($function.'.alink',$domain),
 4156: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4157: 		   'link'    => &designparm($function.'.link',$domain),);
 4158:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4159: 
 4160:  # role and realm
 4161:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4162:     if ($role  eq 'ca') {
 4163:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4164:         $realm = &plainname($rname,$rdom);
 4165:     } 
 4166: # realm
 4167:     if ($env{'request.course.id'}) {
 4168:         if ($env{'request.role'} !~ /^cr/) {
 4169:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4170:         }
 4171: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4172:     } else {
 4173:         $role = &Apache::lonnet::plaintext($role);
 4174:     }
 4175: 
 4176:     if (!$realm) { $realm='&nbsp;'; }
 4177: # Set messages
 4178:     my $messages=&domainlogo($domain);
 4179: 
 4180:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4181: 
 4182: # construct main body tag
 4183:     my $bodytag = "<body $extra_body_attr>".
 4184: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4185: 
 4186:     if ($bodyonly) {
 4187:         return $bodytag;
 4188:     } elsif ($env{'browser.interface'} eq 'textual') {
 4189: # Accessibility
 4190:           
 4191: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4192: 	if (!$notitle) {
 4193: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4194: 	}
 4195: 	return $bodytag;
 4196:     }
 4197: 
 4198:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4199:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4200: 	undef($role);
 4201:     } else {
 4202: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4203:     }
 4204:     
 4205:     my $roleinfo=(<<ENDROLE);
 4206: <td class="LC_title_bar_who">
 4207: <div class="LC_title_bar_name">
 4208:     $name
 4209:     &nbsp;
 4210: </div>
 4211: <div class="LC_title_bar_role">
 4212: $role&nbsp;
 4213: </div>
 4214: <div class="LC_title_bar_realm">
 4215: $realm&nbsp;
 4216: </div>
 4217: </td>
 4218: ENDROLE
 4219: 
 4220:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4221:     if ($customtitle) {
 4222:         $titleinfo = $customtitle;
 4223:     }
 4224:     #
 4225:     # Extra info if you are the DC
 4226:     my $dc_info = '';
 4227:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4228:                         $env{'course.'.$env{'request.course.id'}.
 4229:                                  '.domain'}.'/'})) {
 4230:         my $cid = $env{'request.course.id'};
 4231:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4232:         $dc_info =~ s/\s+$//;
 4233:         $dc_info = '('.$dc_info.')';
 4234:     }
 4235: 
 4236:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4237:         # No Remote
 4238: 	if ($env{'request.state'} eq 'construct') {
 4239: 	    $forcereg=1;
 4240: 	}
 4241: 
 4242: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4243: 	    # this is for resources; directories have customtitle, and crumbs
 4244:             # and select recent are created in lonpubdir.pm  
 4245: 	    my ($uname,$thisdisfn)=
 4246: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4247: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4248: 	    $formaction=~s/\/+/\//g;
 4249: 
 4250: 	    my $parentpath = '';
 4251: 	    my $lastitem = '';
 4252: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4253: 		$parentpath = $1;
 4254: 		$lastitem = $2;
 4255: 	    } else {
 4256: 		$lastitem = $thisdisfn;
 4257: 	    }
 4258: 	    $titleinfo = 
 4259: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4260: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4261: 		.'<form name="dirs" method="post" action="'.$formaction
 4262: 		.'" target="_top"><tt><b>'
 4263: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4264: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4265: 		.'</form>'
 4266: 		.&Apache::lonmenu::constspaceform();
 4267:         }
 4268: 
 4269:         my $titletable;
 4270: 	if (!$notitle) {
 4271: 	    $titletable =
 4272: 		'<table id="LC_title_bar">'.
 4273:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4274: 			 '</tr></table>';
 4275: 	}
 4276: 	if ($notopbar) {
 4277: 	    $bodytag .= $titletable;
 4278: 	} else {
 4279: 	    if ($env{'request.state'} eq 'construct') {
 4280:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4281: 							  $titletable);
 4282:             } else {
 4283:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4284: 		    $titletable;
 4285:             }
 4286:         }
 4287:         return $bodytag;
 4288:     }
 4289: 
 4290: #
 4291: # Top frame rendering, Remote is up
 4292: #
 4293: 
 4294:     my $imgsrc = $img;
 4295:     if ($img =~ /^\/adm/) {
 4296:         $imgsrc = &lonhttpdurl($img);
 4297:     }
 4298:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4299: 
 4300:     # Explicit link to get inline menu
 4301:     my $menu= ($no_inline_link?''
 4302: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4303:     #
 4304:     if ($notitle) {
 4305: 	return $bodytag;
 4306:     }
 4307:     return(<<ENDBODY);
 4308: $bodytag
 4309: <table id="LC_title_bar" class="LC_with_remote">
 4310: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4311:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4312: </tr>
 4313: <tr><td>$titleinfo $dc_info $menu</td>
 4314: $roleinfo
 4315: </tr>
 4316: </table>
 4317: ENDBODY
 4318: }
 4319: 
 4320: sub make_attr_string {
 4321:     my ($register,$attr_ref) = @_;
 4322: 
 4323:     if ($attr_ref && !ref($attr_ref)) {
 4324: 	die("addentries Must be a hash ref ".
 4325: 	    join(':',caller(1))." ".
 4326: 	    join(':',caller(0))." ");
 4327:     }
 4328: 
 4329:     if ($register) {
 4330: 	my ($on_load,$on_unload);
 4331: 	foreach my $key (keys(%{$attr_ref})) {
 4332: 	    if      (lc($key) eq 'onload') {
 4333: 		$on_load.=$attr_ref->{$key}.';';
 4334: 		delete($attr_ref->{$key});
 4335: 
 4336: 	    } elsif (lc($key) eq 'onunload') {
 4337: 		$on_unload.=$attr_ref->{$key}.';';
 4338: 		delete($attr_ref->{$key});
 4339: 	    }
 4340: 	}
 4341: 	$attr_ref->{'onload'}  =
 4342: 	    &Apache::lonmenu::loadevents().  $on_load;
 4343: 	$attr_ref->{'onunload'}=
 4344: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4345:     }
 4346: 
 4347: # Accessibility font enhance
 4348:     if ($env{'browser.fontenhance'} eq 'on') {
 4349: 	my $style;
 4350: 	foreach my $key (keys(%{$attr_ref})) {
 4351: 	    if (lc($key) eq 'style') {
 4352: 		$style.=$attr_ref->{$key}.';';
 4353: 		delete($attr_ref->{$key});
 4354: 	    }
 4355: 	}
 4356: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4357:     }
 4358: 
 4359:     if ($env{'browser.blackwhite'} eq 'on') {
 4360: 	delete($attr_ref->{'font'});
 4361: 	delete($attr_ref->{'link'});
 4362: 	delete($attr_ref->{'alink'});
 4363: 	delete($attr_ref->{'vlink'});
 4364: 	delete($attr_ref->{'bgcolor'});
 4365: 	delete($attr_ref->{'background'});
 4366:     }
 4367: 
 4368:     my $attr_string;
 4369:     foreach my $attr (keys(%$attr_ref)) {
 4370: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4371:     }
 4372:     return $attr_string;
 4373: }
 4374: 
 4375: 
 4376: ###############################################
 4377: ###############################################
 4378: 
 4379: =pod
 4380: 
 4381: =item * &endbodytag()
 4382: 
 4383: Returns a uniform footer for LON-CAPA web pages.
 4384: 
 4385: Inputs: 1 - optional reference to an args hash
 4386: If in the hash, key for noredirectlink has a value which evaluates to true,
 4387: a 'Continue' link is not displayed if the page contains an
 4388: internal redirect in the <head></head> section,
 4389: i.e., $env{'internal.head.redirect'} exists   
 4390: 
 4391: =cut
 4392: 
 4393: sub endbodytag {
 4394:     my ($args) = @_;
 4395:     my $endbodytag='</body>';
 4396:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4397:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4398:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4399: 	    $endbodytag=
 4400: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4401: 	        &mt('Continue').'</a>'.
 4402: 	        $endbodytag;
 4403:         }
 4404:     }
 4405:     return $endbodytag;
 4406: }
 4407: 
 4408: =pod
 4409: 
 4410: =item * &standard_css()
 4411: 
 4412: Returns a style sheet
 4413: 
 4414: Inputs: (all optional)
 4415:             domain         -> force to color decorate a page for a specific
 4416:                                domain
 4417:             function       -> force usage of a specific rolish color scheme
 4418:             bgcolor        -> override the default page bgcolor
 4419: 
 4420: =cut
 4421: 
 4422: sub standard_css {
 4423:     my ($function,$domain,$bgcolor) = @_;
 4424:     $function  = &get_users_function() if (!$function);
 4425:     my $img    = &designparm($function.'.img',   $domain);
 4426:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4427:     my $font   = &designparm($function.'.font',  $domain);
 4428:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4429:     my $pgbg_or_bgcolor =
 4430: 	         $bgcolor ||
 4431: 	         &designparm($function.'.pgbg',  $domain);
 4432:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4433:     my $alink  = &designparm($function.'.alink', $domain);
 4434:     my $vlink  = &designparm($function.'.vlink', $domain);
 4435:     my $link   = &designparm($function.'.link',  $domain);
 4436: 
 4437:     my $loginbg = &designparm('login.sidebg',$domain);
 4438:     my $bgcol = &designparm('login.bgcol',$domain);
 4439:     my $textcol = &designparm('login.textcol',$domain);
 4440: 
 4441:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4442:     my $mono                 = 'monospace';
 4443:     my $data_table_head      = $tabbg;
 4444:     my $data_table_light     = '#EEEEEE';
 4445:     my $data_table_dark      = '#DDDDDD';
 4446:     my $data_table_darker    = '#CCCCCC';
 4447:     my $data_table_highlight = '#FFFF00';
 4448:     my $mail_new             = '#FFBB77';
 4449:     my $mail_new_hover       = '#DD9955';
 4450:     my $mail_read            = '#BBBB77';
 4451:     my $mail_read_hover      = '#999944';
 4452:     my $mail_replied         = '#AAAA88';
 4453:     my $mail_replied_hover   = '#888855';
 4454:     my $mail_other           = '#99BBBB';
 4455:     my $mail_other_hover     = '#669999';
 4456:     my $table_header         = '#DDDDDD';
 4457:     my $feedback_link_bg     = '#BBBBBB';
 4458:     my $lg_border_color	     = '#C8C8C8';
 4459: 
 4460:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4461: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4462: 	                                                 : '0px 3px 0px 4px';
 4463: 
 4464: 
 4465:     return <<END;
 4466: body{
 4467:      font-family: $sans;
 4468:      line-height:130%;
 4469:      font-size:0.83em;
 4470:      color:$font;
 4471:   }
 4472: a:link, a:visited { font-size:100%; }
 4473: 
 4474: a:focus { color: red; background: yellow } 
 4475: table.thinborder,
 4476: table.thinborder tr th {
 4477:   border-style: solid;
 4478:   border-width: 1px;
 4479:   border-color: $lg_border_color;
 4480:   background: $tabbg;
 4481: }
 4482: table.thinborder tr td {
 4483:   border-style: solid;
 4484:   border-width: 1px;
 4485:   border-color: $lg_border_color;
 4486: }
 4487: 
 4488: form, .inline { display: inline; }
 4489: 
 4490: .LC_center { text-align: center; }
 4491: .LC_left { text-align:left; }
 4492: .LC_right {text-align:right;}
 4493: .LC_middle {vertical-align:middle;}
 4494: .LC_top {vertical-align:top;}
 4495: .LC_bottom {vertical-align:bottom;}
 4496: 
 4497: /* just for tests */
 4498: .LC_300Box { width:300px; }
 4499: .LC_200Box {width:200px; }
 4500: .LC_500Box {width:500px; }
 4501: .LC_600Box {width:600px; }
 4502: /* end */
 4503: 
 4504: .LC_filename {font-family: $mono; white-space:pre;}
 4505: .LC_error {
 4506:   color: red;
 4507:   font-size: larger;
 4508: }
 4509: .LC_warning,
 4510: .LC_diff_removed {
 4511:   color: red;
 4512: }
 4513: 
 4514: .LC_info,
 4515: .LC_success,
 4516: .LC_diff_added {
 4517:   color: green;
 4518: }
 4519: .LC_unknown {
 4520:   color: yellow;
 4521: }
 4522: 
 4523: .LC_icon {
 4524:   border: 0px;
 4525: }
 4526: .LC_indexer_icon {
 4527:   border: 0px;
 4528:   height: 22px;
 4529: }
 4530: .LC_docs_spacer {
 4531:   width: 25px;
 4532:   height: 1px;
 4533:   border: 0px;
 4534: }
 4535: 
 4536: .LC_internal_info {
 4537:   color: #999999;
 4538: }
 4539: 
 4540: table.LC_pastsubmission {
 4541:   border: 1px solid black;
 4542:   margin: 2px;
 4543: }
 4544: 
 4545: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4546:   width: 100%;
 4547:   background: $pgbg;
 4548:   border: 2px;
 4549:   border-collapse: separate;
 4550:   padding: 0px;
 4551: }
 4552: 
 4553: table#LC_title_bar, table.LC_breadcrumbs, 
 4554: table#LC_title_bar.LC_with_remote {
 4555:   width: 100%;
 4556:   border-color: $pgbg;
 4557:   border-style: solid;
 4558:   border-width: $border;
 4559: 
 4560:   background: $pgbg;
 4561:   font-family: $sans;
 4562:   border-collapse: collapse;
 4563:   padding: 0px;
 4564: }
 4565: table.LC_docs_path {
 4566:   width: 100%;
 4567:   border: 0;
 4568:   background: $pgbg;
 4569:   font-family: $sans;
 4570:   border-collapse: collapse;
 4571:   padding: 0px;
 4572: }
 4573: 
 4574: table#LC_title_bar td {
 4575:   background: $tabbg;
 4576: }
 4577: table#LC_title_bar td.LC_title_bar_who {
 4578:   background: $tabbg;
 4579:   color: $font;
 4580:   font: small $sans;
 4581:   text-align: right;
 4582: }
 4583: span.LC_metadata {
 4584:     font-family: $sans;
 4585: }
 4586: span.LC_title_bar_title {
 4587:   font: bold x-large $sans;
 4588: }
 4589: table#LC_title_bar td.LC_title_bar_domain_logo {
 4590:   background: $sidebg;
 4591:   text-align: right;
 4592:   padding: 0px;
 4593: }
 4594: table#LC_title_bar td.LC_title_bar_role_logo {
 4595:   background: $sidebg;
 4596:   padding: 0px;
 4597: }
 4598: 
 4599: table#LC_menubuttons img{
 4600:   border: 0px;
 4601: }
 4602: table#LC_top_nav td {
 4603:   background: $tabbg;
 4604:   border: 0px;
 4605:   font-size: small;
 4606:   vertical-align:top;
 4607:   padding:2px 5px 2px 5px;
 4608: }
 4609: table#LC_top_nav td a, div#LC_top_nav a {
 4610:   color: $font;
 4611:   font-family: $sans;
 4612: }
 4613: table#LC_top_nav td.LC_top_nav_logo {
 4614:   background: $tabbg;
 4615:   text-align: left;
 4616:   white-space: nowrap;
 4617:   width: 31px;
 4618: }
 4619: table#LC_top_nav td.LC_top_nav_logo img {
 4620:   border: 0px;
 4621:   vertical-align: bottom;
 4622: }
 4623: table#LC_top_nav td.LC_top_nav_exit,
 4624: table#LC_top_nav td.LC_top_nav_help {
 4625:   width: 2.0em;
 4626: }
 4627: table#LC_top_nav td.LC_top_nav_login {
 4628:   width: 4.0em;
 4629:   text-align: center;
 4630: }
 4631: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4632:   background: $tabbg;
 4633:   color: $font;
 4634:   font-family: $sans;
 4635:   font-size: smaller;
 4636: }
 4637: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4638: table.LC_docs_path td.LC_docs_path_component {
 4639:   background: $tabbg;
 4640:   color: $font;
 4641:   font-family: $sans;
 4642:   font-size: larger;
 4643:   text-align: right;
 4644: }
 4645: td.LC_table_cell_checkbox {
 4646:   text-align: center;
 4647: }
 4648: table#LC_mainmenu td.LC_mainmenu_column {
 4649:     vertical-align: top;
 4650: }
 4651: 
 4652: .LC_fontsize_small
 4653: {
 4654:  font-size: 70%;
 4655: }
 4656: 
 4657: .LC_fontsize_medium
 4658: {
 4659:  font-size: 85%;
 4660: }
 4661: 
 4662: .LC_fontsize_large
 4663: {
 4664:  font-size: 120%;
 4665: }
 4666: 
 4667: .LC_fontcolor_red
 4668: {
 4669:  color: #FF0000;
 4670: }
 4671: 
 4672: .LC_menubuttons_inline_text {
 4673:   color: $font;
 4674:   font-family: $sans;
 4675:   font-size: 90%;
 4676:   padding-left:3px;
 4677: }
 4678: 
 4679: .LC_menubuttons_link {
 4680:   text-decoration: none;
 4681: }
 4682: /*2008--9-5: new menu style sheet.Changed category*/
 4683: .LC_menubuttons_category {
 4684:   color: $font;
 4685:   background: $pgbg;
 4686:   font-family: $sans;
 4687:   font-size: larger;
 4688:   font-weight: bold;
 4689: }
 4690: 
 4691: td.LC_menubuttons_text {
 4692:  	color: $font; 	
 4693: }
 4694: 
 4695: 
 4696: 
 4697: .LC_current_location {
 4698:   font-family: $sans;
 4699:   background: $tabbg;
 4700: }
 4701: .LC_new_mail {
 4702:   font-family: $sans;
 4703:   background: $tabbg;
 4704:   font-weight: bold;
 4705: }
 4706: 
 4707: 
 4708: .LC_dropadd_labeltext {
 4709:   font-family: $sans;
 4710:   text-align: right;
 4711: }
 4712: 
 4713: .LC_preferences_labeltext {
 4714:   font-family: $sans;
 4715:   text-align: right;
 4716: }
 4717: 
 4718: .LC_roleslog_note {
 4719:   font-size: small;
 4720: }
 4721: 
 4722: .LC_mail_functions {
 4723:     font-weight: bold;
 4724: }
 4725: 
 4726: table.LC_aboutme_port {
 4727:   border: 0px;
 4728:   border-collapse: collapse;
 4729:   border-spacing: 0px;
 4730: }
 4731: table.LC_data_table, table.LC_mail_list {
 4732:   border: 1px solid #000000;
 4733:   border-collapse: separate;
 4734:   border-spacing: 1px;
 4735:   background: $pgbg;
 4736: }
 4737: .LC_data_table_dense {
 4738:   font-size: small;
 4739: }
 4740: table.LC_nested_outer {
 4741:   border: 1px solid #000000;
 4742:   border-collapse: collapse;
 4743:   border-spacing: 0px;
 4744:   width: 100%;
 4745: }
 4746: table.LC_nested {
 4747:   border: 0px;
 4748:   border-collapse: collapse;
 4749:   border-spacing: 0px;
 4750:   width: 100%;
 4751: }
 4752: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4753: table.LC_prior_tries tr th {
 4754:   font-weight: bold;
 4755:   background-color: $data_table_head;
 4756:   font-size:90%;
 4757: }
 4758: table.LC_data_table tr.LC_info_row > td {
 4759:   background-color: #CCCCCC;
 4760:   font-weight: bold;
 4761:   text-align: left;
 4762: }
 4763: table.LC_data_table tr.LC_odd_row > td, 
 4764: table.LC_pick_box tr > td.LC_odd_row,
 4765: table.LC_aboutme_port tr td {
 4766:   background-color: $data_table_light;
 4767:   padding: 2px;
 4768: }
 4769: table.LC_data_table tr.LC_even_row > td,
 4770: table.LC_pick_box tr > td.LC_even_row,
 4771: table.LC_aboutme_port tr.LC_even_row td {
 4772:   background-color: $data_table_dark;
 4773:   padding: 2px;
 4774: }
 4775: table.LC_data_table tr.LC_data_table_highlight td {
 4776:   background-color: $data_table_darker;
 4777: }
 4778: table.LC_data_table tr td.LC_leftcol_header {
 4779:   background-color: $data_table_head;
 4780:   font-weight: bold;
 4781: }
 4782: table.LC_data_table tr.LC_empty_row td,
 4783: table.LC_nested tr.LC_empty_row td {
 4784:   background-color: #FFFFFF;
 4785:   font-weight: bold;
 4786:   font-style: italic;
 4787:   text-align: center;
 4788:   padding: 8px;
 4789: }
 4790: table.LC_nested tr.LC_empty_row td {
 4791:   padding: 4ex
 4792: }
 4793: table.LC_nested_outer tr th {
 4794:   font-weight: bold;
 4795:   background-color: $data_table_head;
 4796:   font-size: small;
 4797:   border-bottom: 1px solid #000000;
 4798: }
 4799: table.LC_nested_outer tr td.LC_subheader {
 4800:   background-color: $data_table_head;
 4801:   font-weight: bold;
 4802:   font-size: small;
 4803:   border-bottom: 1px solid #000000;
 4804:   text-align: right;
 4805: }
 4806: table.LC_nested tr.LC_info_row td {
 4807:   background-color: #CCCCCC;
 4808:   font-weight: bold;
 4809:   font-size: small;
 4810:   text-align: center;
 4811: }
 4812: table.LC_nested tr.LC_info_row td.LC_left_item,
 4813: table.LC_nested_outer tr th.LC_left_item {
 4814:   text-align: left;
 4815: }
 4816: table.LC_nested td {
 4817:   background-color: #FFFFFF;
 4818:   font-size: small;
 4819: }
 4820: table.LC_nested_outer tr th.LC_right_item,
 4821: table.LC_nested tr.LC_info_row td.LC_right_item,
 4822: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4823: table.LC_nested tr td.LC_right_item {
 4824:   text-align: right;
 4825: }
 4826: 
 4827: table.LC_nested tr.LC_odd_row td {
 4828:   background-color: #EEEEEE;
 4829: }
 4830: 
 4831: table.LC_createuser {
 4832: }
 4833: 
 4834: table.LC_createuser tr.LC_section_row td {
 4835:   font-size: small;
 4836: }
 4837: 
 4838: table.LC_createuser tr.LC_info_row td  {
 4839:   background-color: #CCCCCC;
 4840:   font-weight: bold;
 4841:   text-align: center;
 4842: }
 4843: 
 4844: table.LC_calendar {
 4845:   border: 1px solid #000000;
 4846:   border-collapse: collapse;
 4847: }
 4848: table.LC_calendar_pickdate {
 4849:   font-size: xx-small;
 4850: }
 4851: table.LC_calendar tr td {
 4852:   border: 1px solid #000000;
 4853:   vertical-align: top;
 4854: }
 4855: table.LC_calendar tr td.LC_calendar_day_empty {
 4856:   background-color: $data_table_dark;
 4857: }
 4858: table.LC_calendar tr td.LC_calendar_day_current {
 4859:   background-color: $data_table_highlight;
 4860: }
 4861: 
 4862: table.LC_mail_list tr.LC_mail_new {
 4863:   background-color: $mail_new;
 4864: }
 4865: table.LC_mail_list tr.LC_mail_new:hover {
 4866:   background-color: $mail_new_hover;
 4867: }
 4868: table.LC_mail_list tr.LC_mail_read {
 4869:   background-color: $mail_read;
 4870: }
 4871: table.LC_mail_list tr.LC_mail_read:hover {
 4872:   background-color: $mail_read_hover;
 4873: }
 4874: table.LC_mail_list tr.LC_mail_replied {
 4875:   background-color: $mail_replied;
 4876: }
 4877: table.LC_mail_list tr.LC_mail_replied:hover {
 4878:   background-color: $mail_replied_hover;
 4879: }
 4880: table.LC_mail_list tr.LC_mail_other {
 4881:   background-color: $mail_other;
 4882: }
 4883: table.LC_mail_list tr.LC_mail_other:hover {
 4884:   background-color: $mail_other_hover;
 4885: }
 4886: table.LC_mail_list tr.LC_mail_even {
 4887: }
 4888: table.LC_mail_list tr.LC_mail_odd {
 4889: }
 4890: 
 4891: table.LC_data_table tr > td.LC_browser_file,
 4892: table.LC_data_table tr > td.LC_browser_file_published {
 4893:   background: #CCFF88;
 4894: }
 4895: table.LC_data_table tr > td.LC_browser_file_locked,
 4896: table.LC_data_table tr > td.LC_browser_file_unpublished {
 4897:   background: #FFAA99;
 4898: }
 4899: table.LC_data_table tr > td.LC_browser_file_obsolete {
 4900:   background: #AAAAAA;
 4901: }
 4902: table.LC_data_table tr > td.LC_browser_file_modified,
 4903: table.LC_data_table tr > td.LC_browser_file_metamodified {
 4904:   background: #FFFF77;
 4905: }
 4906: table.LC_data_table tr.LC_browser_folder > td {
 4907:   background: #CCCCFF;
 4908: }
 4909: 
 4910: table.LC_data_table tr > td.LC_roles_is {
 4911: /*  background: #77FF77; */
 4912: }
 4913: table.LC_data_table tr > td.LC_roles_future {
 4914:   background: #FFFF77;
 4915: }
 4916: table.LC_data_table tr > td.LC_roles_will {
 4917:   background: #FFAA77;
 4918: }
 4919: table.LC_data_table tr > td.LC_roles_expired {
 4920:   background: #FF7777;
 4921: }
 4922: table.LC_data_table tr > td.LC_roles_will_not {
 4923:   background: #AAFF77;
 4924: }
 4925: table.LC_data_table tr > td.LC_roles_selected {
 4926:   background: #11CC55;
 4927: }
 4928: 
 4929: span.LC_current_location {
 4930:   font-size:larger;
 4931:   background: $pgbg;
 4932: }
 4933: 
 4934: span.LC_parm_menu_item {
 4935:   font-size: larger;
 4936:   font-family: $sans;
 4937: }
 4938: span.LC_parm_scope_all {
 4939:   color: red;
 4940: }
 4941: span.LC_parm_scope_folder {
 4942:   color: green;
 4943: }
 4944: span.LC_parm_scope_resource {
 4945:   color: orange;
 4946: }
 4947: span.LC_parm_part {
 4948:   color: blue;
 4949: }
 4950: span.LC_parm_folder, span.LC_parm_symb {
 4951:   font-size: x-small;
 4952:   font-family: $mono;
 4953:   color: #AAAAAA;
 4954: }
 4955: 
 4956: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4957: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4958:   border: 1px solid black;
 4959:   border-collapse: collapse;
 4960: }
 4961: table.LC_parm_overview_restrictions td {
 4962:   border-width: 1px 4px 1px 4px;
 4963:   border-style: solid;
 4964:   border-color: $pgbg;
 4965:   text-align: center;
 4966: }
 4967: table.LC_parm_overview_restrictions th {
 4968:   background: $tabbg;
 4969:   border-width: 1px 4px 1px 4px;
 4970:   border-style: solid;
 4971:   border-color: $pgbg;
 4972: }
 4973: table#LC_helpmenu {
 4974:   border: 0px;
 4975:   height: 55px;
 4976:   border-spacing: 0px;
 4977: }
 4978: 
 4979: table#LC_helpmenu fieldset legend {
 4980:   font-size: larger;
 4981:   font-weight: bold;
 4982: }
 4983: table#LC_helpmenu_links {
 4984:   width: 100%;
 4985:   border: 1px solid black;
 4986:   background: $pgbg;
 4987:   padding: 0px;
 4988:   border-spacing: 1px;
 4989: }
 4990: table#LC_helpmenu_links tr td {
 4991:   padding: 1px;
 4992:   background: $tabbg;
 4993:   text-align: center;
 4994:   font-weight: bold;
 4995: }
 4996: 
 4997: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 4998: table#LC_helpmenu_links a:active {
 4999:   text-decoration: none;
 5000:   color: $font;
 5001: }
 5002: table#LC_helpmenu_links a:hover {
 5003:   text-decoration: underline;
 5004:   color: $vlink;
 5005: }
 5006: 
 5007: .LC_chrt_popup_exists {
 5008:   border: 1px solid #339933;
 5009:   margin: -1px;
 5010: }
 5011: .LC_chrt_popup_up {
 5012:   border: 1px solid yellow;
 5013:   margin: -1px;
 5014: }
 5015: .LC_chrt_popup {
 5016:   border: 1px solid #8888FF;
 5017:   background: #CCCCFF;
 5018: }
 5019: table.LC_pick_box {
 5020:   border-collapse: separate;
 5021:   background: white;
 5022:   border: 1px solid black;
 5023:   border-spacing: 1px;
 5024: }
 5025: table.LC_pick_box td.LC_pick_box_title {
 5026:   background: $tabbg;
 5027:   font-weight: bold;
 5028:   text-align: right;
 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: .LC_answer_no_message {
 5210:   background: #FFFFFF;
 5211:   color: black;
 5212: }
 5213: .LC_answer_unknown {
 5214:   background: orange;
 5215:   color: black;
 5216: }
 5217: 
 5218: 
 5219: span.LC_prior_numerical,
 5220: span.LC_prior_string,
 5221: span.LC_prior_custom,
 5222: span.LC_prior_reaction,
 5223: span.LC_prior_math {
 5224:   font-family: monospace;
 5225:   white-space: pre;
 5226: }
 5227: 
 5228: span.LC_prior_string {
 5229:   font-family: monospace;
 5230:   white-space: pre;
 5231: }
 5232: 
 5233: table.LC_prior_option {
 5234:   width: 100%;
 5235:   border-collapse: collapse;
 5236: }
 5237: table.LC_prior_rank, table.LC_prior_match {
 5238:   border-collapse: collapse;
 5239: }
 5240: table.LC_prior_option tr td,
 5241: table.LC_prior_rank tr td,
 5242: table.LC_prior_match tr td {
 5243:   border: 1px solid #000000;
 5244: }
 5245: 
 5246: span.LC_nobreak {
 5247:   white-space: nowrap;
 5248: }
 5249: 
 5250: span.LC_cusr_emph {
 5251:   font-style: italic;
 5252: }
 5253: 
 5254: span.LC_cusr_subheading {
 5255:   font-weight: normal;
 5256:   font-size: 85%;
 5257: }
 5258: 
 5259: table.LC_docs_documents {
 5260:   background: #BBBBBB;
 5261:   border-width: 0px;
 5262:   border-collapse: collapse;
 5263: }
 5264: 
 5265: table.LC_docs_documents td.LC_docs_document {
 5266:   border: 2px solid black;
 5267:   padding: 4px;
 5268: }
 5269: 
 5270: .LC_docs_entry_move {
 5271:   border: 0px;
 5272:   border-collapse: collapse;
 5273: }
 5274: 
 5275: .LC_docs_entry_move td {
 5276:   border: 2px solid #BBBBBB;
 5277:   background: #DDDDDD;
 5278: }
 5279: 
 5280: .LC_docs_editor td.LC_docs_entry_commands {
 5281:   background: #DDDDDD;
 5282:   font-size: x-small;
 5283: }
 5284: .LC_docs_copy {
 5285:   color: #000099;
 5286: }
 5287: .LC_docs_cut {
 5288:   color: #550044;
 5289: }
 5290: .LC_docs_rename {
 5291:   color: #009900;
 5292: }
 5293: .LC_docs_remove {
 5294:   color: #990000;
 5295: }
 5296: 
 5297: .LC_docs_reinit_warn,
 5298: .LC_docs_ext_edit {
 5299:   font-size: x-small;
 5300: }
 5301: 
 5302: .LC_docs_editor td.LC_docs_entry_title,
 5303: .LC_docs_editor td.LC_docs_entry_icon {
 5304:   background: #FFFFBB;
 5305: }
 5306: .LC_docs_editor td.LC_docs_entry_parameter {
 5307:   background: #BBBBFF;
 5308:   font-size: x-small;
 5309:   white-space: nowrap;
 5310: }
 5311: 
 5312: table.LC_docs_adddocs td,
 5313: table.LC_docs_adddocs th {
 5314:   border: 1px solid #BBBBBB;
 5315:   padding: 4px;
 5316:   background: #DDDDDD;
 5317: }
 5318: 
 5319: table.LC_sty_begin {
 5320:   background: #BBFFBB;
 5321: }
 5322: table.LC_sty_end {
 5323:   background: #FFBBBB;
 5324: }
 5325: 
 5326: table.LC_double_column {
 5327:   border-width: 0px;
 5328:   border-collapse: collapse;
 5329:   width: 100%;
 5330:   padding: 2px;
 5331: }
 5332: 
 5333: table.LC_double_column tr td.LC_left_col {
 5334:   top: 2px;
 5335:   left: 2px;
 5336:   width: 47%;
 5337:   vertical-align: top;
 5338: }
 5339: 
 5340: table.LC_double_column tr td.LC_right_col {
 5341:   top: 2px;
 5342:   right: 2px; 
 5343:   width: 47%;
 5344:   vertical-align: top;
 5345: }
 5346: 
 5347: span.LC_role_level {
 5348:   font-weight: bold;
 5349: }
 5350: 
 5351: div.LC_left_float {
 5352:   float: left;
 5353:   padding-right: 5%;
 5354:   padding-bottom: 4px;
 5355: }
 5356: 
 5357: div.LC_clear_float_header {
 5358:   padding-bottom: 2px;
 5359: }
 5360: 
 5361: div.LC_clear_float_footer {
 5362:   padding-top: 10px;
 5363:   clear: both;
 5364: }
 5365: 
 5366: 
 5367: div.LC_grade_show_user {
 5368:   margin-top: 20px;
 5369:   border: 1px solid black;
 5370: }
 5371: div.LC_grade_user_name {
 5372:   background: #DDDDEE;
 5373:   border-bottom: 1px solid black;
 5374:   font-weight: bold;
 5375:   font-size: large;
 5376: }
 5377: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5378:   background: #DDEEDD;
 5379: }
 5380: 
 5381: div.LC_grade_show_problem,
 5382: div.LC_grade_submissions,
 5383: div.LC_grade_message_center,
 5384: div.LC_grade_info_links,
 5385: div.LC_grade_assign {
 5386:   margin: 5px;
 5387:   width: 99%;
 5388:   background: #FFFFFF;
 5389: }
 5390: div.LC_grade_show_problem_header,
 5391: div.LC_grade_submissions_header,
 5392: div.LC_grade_message_center_header,
 5393: div.LC_grade_assign_header {
 5394:   font-weight: bold;
 5395:   font-size: large;
 5396: }
 5397: div.LC_grade_show_problem_problem,
 5398: div.LC_grade_submissions_body,
 5399: div.LC_grade_message_center_body,
 5400: div.LC_grade_assign_body {
 5401:   border: 1px solid black;
 5402:   width: 99%;
 5403:   background: #FFFFFF;
 5404: }
 5405: span.LC_grade_check_note {
 5406:   font-weight: normal;
 5407:   font-size: medium;
 5408:   display: inline;
 5409:   position: absolute;
 5410:   right: 1em;
 5411: }
 5412: 
 5413: table.LC_scantron_action {
 5414:   width: 100%;
 5415: }
 5416: table.LC_scantron_action tr th {
 5417:   font-weight:bold;
 5418:   font-style:normal;
 5419: }
 5420: .LC_edit_problem_header, 
 5421: div.LC_edit_problem_footer {
 5422:   font-weight: normal;
 5423:   font-size:  medium;
 5424:   margin: 2px;
 5425: }
 5426: div.LC_edit_problem_header,
 5427: div.LC_edit_problem_header div,
 5428: div.LC_edit_problem_footer,
 5429: div.LC_edit_problem_footer div,
 5430: div.LC_edit_problem_editxml_header,
 5431: div.LC_edit_problem_editxml_header div {
 5432:   margin-top: 5px;
 5433: }
 5434: div.LC_edit_problem_header_edit_row {
 5435:   background: $tabbg;
 5436:   padding: 3px;
 5437:   margin-bottom: 5px;
 5438: }
 5439: div.LC_edit_problem_header_title {
 5440:   font-weight: bold;
 5441:   font-size: larger;
 5442:   background: $tabbg;
 5443:   padding: 3px;
 5444: }
 5445: table.LC_edit_problem_header_title {
 5446:   font-size: larger;
 5447:   font-weight:  bold;
 5448:   width: 100%;
 5449:   border-color: $pgbg;
 5450:   border-style: solid;
 5451:   border-width: $border;
 5452: 
 5453:   background: $tabbg;
 5454:   border-collapse: collapse;
 5455:   padding: 0px
 5456: }
 5457: 
 5458: div.LC_edit_problem_discards {
 5459:   float: left;
 5460:   padding-bottom: 5px;
 5461: }
 5462: div.LC_edit_problem_saves {
 5463:   float: right;
 5464:   padding-bottom: 5px;
 5465: }
 5466: hr.LC_edit_problem_divide {
 5467:   clear: both;
 5468:   color: $tabbg;
 5469:   background-color: $tabbg;
 5470:   height: 3px;
 5471:   border: 0px;
 5472: }
 5473: img.stift{
 5474:   border-width:0;
 5475:   vertical-align:middle;
 5476: }
 5477: 
 5478: table#LC_mainmenu{
 5479:  margin-top:10px;
 5480:  width:80%;
 5481: 
 5482: }
 5483: 
 5484: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5485:   vertical-align: top;
 5486:   width: 45%;
 5487: }
 5488: .LC_mainmenu_fieldset_category {
 5489:   color: $font;
 5490:   background: $pgbg;
 5491:   font-family: $sans;
 5492:   font-size: small;
 5493:   font-weight: bold;
 5494: }
 5495: 
 5496: div.LC_createcourse {
 5497:     margin: 10px 10px 10px 10px;
 5498: }
 5499: 
 5500: /* ---- Remove when done ----
 5501: # The following styles is part of the redesign of LON-CAPA and are
 5502: # subject to change during this project.
 5503: # Don't rely on their current functionality as they might be 
 5504: # changed or removed.
 5505: # --------------------------*/
 5506: 
 5507: a:hover,
 5508: ol.LC_smallMenu a:hover,
 5509: ol#LC_MenuBreadcrumbs a:hover,
 5510: ol#LC_PathBreadcrumbs a:hover,
 5511: ul#LC_TabMainMenuContent a:hover,
 5512: .LC_FormSectionClearButton input:hover
 5513: ul.LC_TabContent   li:hover a{
 5514: 	color:#BF2317;
 5515:         text-decoration:none;
 5516: }
 5517: 
 5518: h1 { 
 5519: 	padding:5px 10px 5px 20px;
 5520: 	line-height:130%;
 5521: }
 5522: 
 5523: h2,h3,h4,h5,h6
 5524: {
 5525: 	margin:5px 0px 5px 0px;
 5526: 	padding:0px;
 5527: 	line-height:130%;
 5528: }
 5529: .LC_hcell{
 5530:         padding:3px 15px 3px 15px;
 5531:         margin:0px;
 5532: 	background-color:$tabbg;
 5533: 	border-bottom:solid 1px $lg_border_color;       
 5534: }
 5535: .LC_noBorder {
 5536:         border:0px;
 5537: }
 5538: 
 5539: .LC_bgLightGrey{
 5540: 	background:URL(/adm/lonIcons/lightGreyBG.png) repeat-x left top; 
 5541: }
 5542: .LC_bgLightGreyYellow {
 5543: 	background-color:#EFECE0;
 5544: }
 5545: 
 5546: /* Main Header with discription of Person, Course, etc. */
 5547: .LC_HeadRight {
 5548: 	text-align: right;
 5549: 	float: right;
 5550: 	margin: 0px;
 5551: 	padding: 0px;
 5552:         right:0;
 5553:         position:absolute;
 5554:         overflow:hidden;
 5555: }
 5556: 
 5557: p, .LC_ContentBox {
 5558: 	padding: 10px;
 5559: 
 5560: }
 5561: .LC_FormSectionClearButton input {
 5562:     	    
 5563:         border:0px;
 5564:         cursor:pointer;
 5565:         text-decoration:underline;
 5566: }
 5567: 
 5568: 
 5569: dl,ul,div,fieldset {
 5570: 	margin: 10px 10px 10px 0px;
 5571: 	overflow:hidden;
 5572: }
 5573: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5574: 	margin: 0px;
 5575: }
 5576: 
 5577: ol.LC_smallMenu li {
 5578: 	display: inline;
 5579: 	padding: 5px 5px 0px 10px;
 5580: 	vertical-align: top;
 5581: }
 5582: 
 5583: ol.LC_smallMenu li img {
 5584: 	vertical-align: bottom;
 5585: }
 5586: 
 5587: ol.LC_smallMenu a {
 5588: 	font-size: 90%;
 5589: 	color: RGB(80, 80, 80);
 5590: 	text-decoration: none;
 5591: }
 5592: 
 5593: ol#LC_TabMainMenuContent {
 5594: 	display:block;
 5595: 	list-style:none;
 5596: 	margin: 0px 0px 10px 0px;
 5597: 	padding: 0px;
 5598: }
 5599: 
 5600: ol#LC_TabMainMenuContent li {
 5601: 	display: inline;
 5602: 	vertical-align: bottom;
 5603: 	border-bottom: solid 1px RGB(175, 175, 175);
 5604: 	border-right: solid 1px RGB(175, 175, 175);
 5605: 	padding: 5px 10px 5px 10px;
 5606: 	margin-right:3px;
 5607: 	line-height: 140%;
 5608: 	font-weight: bold;
 5609: 	white-space:nowrap;
 5610: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5611: }
 5612: 
 5613: ol#LC_TabMainMenuContent li a{
 5614: 	color: RGB(47, 47, 47);
 5615: 	text-decoration: none;
 5616: }
 5617: ul.LC_TabContent {
 5618: 	margin:0px;
 5619: 	padding:0px;
 5620: 	display:block;
 5621: 	list-style:none;
 5622: 	min-height:1.5em;
 5623: }
 5624: ul.LC_TabContent li{
 5625: 	display:inline;
 5626: 	vertical-align:top;
 5627: 	border-bottom:solid 1px $lg_border_color;
 5628: 	border-right:solid 1px $lg_border_color;
 5629: 	padding:5px 10px 5px 10px;
 5630: 	margin-right:2px;
 5631: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5632: }
 5633: ul.LC_TabContent li a, ul.LC_TabContent li{
 5634: 	color:rgb(47,47,47);
 5635: 	text-decoration:none;
 5636: 	font-size:95%;
 5637: 	font-weight:bold;
 5638: 	white-space:nowrap;
 5639: }
 5640: .LC_hideThis
 5641: {
 5642: 	display:none;
 5643: 	visibility:hidden;
 5644: }
 5645: 
 5646: ol#LC_MenuBreadcrumbs, ol#LC_PathBreadcrumbs {
 5647: 	border-top: solid 1px RGB(255, 255, 255);
 5648: 	height: 20px;
 5649: 	line-height: 20px;
 5650: 	vertical-align: bottom;
 5651: 	margin: 0px 0px 30px 0px;
 5652: 	padding-left: 10px;
 5653: 	list-style-position: inside;
 5654: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5655: }
 5656: 
 5657: ol#LC_MenuBreadcrumbs li, ol#LC_PathBreadcrumbs li {
 5658: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5659: 	display: inline;
 5660: 	padding: 0px 0px 0px 10px;
 5661: 	vertical-align: bottom;
 5662: 	overflow:hidden;
 5663: }
 5664: 
 5665: ol#LC_MenuBreadcrumbs li a {
 5666: 	text-decoration: none;
 5667: 	font-size:90%;
 5668: }
 5669: ol#LC_PathBreadcrumbs li a{
 5670: 	text-decoration:none;
 5671: 	font-size:100%;
 5672: 	font-weight:bold;
 5673: }
 5674: .LC_ContentBoxSpecial
 5675: {
 5676: 	border: solid 1px $lg_border_color;
 5677: }
 5678: .LC_PopUp
 5679: {
 5680: 	padding:10px;
 5681: 	border-left:solid 1px $lg_border_color;
 5682:  	border-top:solid 1px $lg_border_color;
 5683: 	border-bottom:outset 1px $lg_border_color;
 5684: 	border-right:outset 1px $lg_border_color;
 5685: 	display:none;
 5686: 	position:absolute;
 5687: 	right:0;
 5688: 	background-color:white;
 5689: 	z-index:5;
 5690: }
 5691: 
 5692: dl.LC_ListStyleClean dt {
 5693: 	padding-right: 5px;
 5694: 	display: table-header-group;
 5695: }
 5696: 
 5697: dl.LC_ListStyleClean dd {
 5698: 	display: table-row;
 5699: }
 5700: 
 5701: .LC_ListStyleClean,
 5702: .LC_ListStyleSimple,
 5703: .LC_ListStyleNormal,
 5704: .LC_ListStyleNormal_Border,
 5705: .LC_ListStyleSpecial
 5706: 	{
 5707: 	/*display:block;	*/
 5708: 	list-style-position: inside;
 5709: 	list-style-type: none;
 5710: 	overflow: hidden;
 5711: 	padding: 0px;
 5712: }
 5713: 
 5714: .LC_ListStyleSimple li,
 5715: .LC_ListStyleSimple dd,
 5716: .LC_ListStyleNormal li,
 5717: .LC_ListStyleNormal dd,
 5718: .LC_ListStyleSpecial li,
 5719: .LC_ListStyleSpecial dd
 5720: 	{
 5721: 	margin: 0px;
 5722: 	padding: 5px 5px 5px 10px;
 5723: 	clear: both;
 5724: }
 5725: 
 5726: .LC_ListStyleClean li,
 5727: .LC_ListStyleClean dd {
 5728: 	padding-top: 0px;
 5729: 	padding-bottom: 0px;
 5730: }
 5731: 
 5732: .LC_ListStyleSimple dd,
 5733: .LC_ListStyleSimple li{
 5734: 	border-bottom: solid 1px $lg_border_color;
 5735: }
 5736: 
 5737: .LC_ListStyleSpecial li,
 5738: .LC_ListStyleSpecial dd {
 5739: 	list-style-type: none;
 5740: 	background-color: RGB(220, 220, 220);
 5741: 	margin-bottom: 4px;
 5742: }
 5743: 
 5744: table.LC_SimpleTable {
 5745: 	margin:5px;
 5746: 	border:solid 1px $lg_border_color;
 5747: 	}
 5748: 
 5749: table.LC_SimpleTable tr {
 5750: 	padding:0px;
 5751: 	border:solid 1px $lg_border_color;
 5752: }
 5753: table.LC_SimpleTable thead{
 5754: 	 background:rgb(220,220,220);
 5755: }
 5756: 
 5757: div.LC_columnSection {
 5758: 	display: block;
 5759: 	clear: both;
 5760: 	overflow: hidden;
 5761: 	margin:0px;
 5762: }
 5763: 
 5764: div.LC_columnSection>* {
 5765: 	float: left;
 5766: 	margin: 10px 20px 10px 0px;
 5767: 	overflow:hidden;	
 5768: }
 5769: div.LC_columnSection > .LC_ContentBox,
 5770: div.LC_columnSection > .LC_ContentBoxSpecial
 5771: 	{
 5772: 	width: 400px;	
 5773: }
 5774: 
 5775: .ContentBoxSpecialTemplate
 5776: {
 5777:         border: solid 1px $lg_border_color;
 5778: }
 5779: .ContentBoxTemplate {
 5780:         padding:10px;
 5781: }
 5782: 
 5783: div.LC_columnSection > .ContentBoxTemplate,
 5784: div.LC_columnSection > .ContentBoxSpecialTemplate
 5785:         {
 5786:         width: 600px;
 5787: 
 5788: }
 5789: 
 5790: .clear{
 5791: 	clear: both;
 5792: 	line-height: 0px;
 5793: 	font-size: 0px;
 5794: 	height: 0px;
 5795: }
 5796: 
 5797: .LC_loginpage_container {
 5798: 	text-align:left;
 5799: 	margin : 0 auto;
 5800: 	width:65%;
 5801: 	padding: 10px;
 5802: 	height: auto;
 5803: 	background-color:#FFFFFF;
 5804: 	border:1px solid #CCCCCC;
 5805: }
 5806: 
 5807: 
 5808: .LC_loginpage_loginContainer {
 5809: 	float:left;
 5810: 	width: 182px;
 5811: 	border:1px solid #CCCCCC;
 5812: 	background-color:$loginbg;
 5813: }
 5814: 
 5815: .LC_loginpage_loginContainer h2{
 5816: 	margin-top:0;
 5817: 	display:block;
 5818: 	background:$bgcol;
 5819: 	color:$textcol;
 5820: 	padding-left:5px;
 5821: }
 5822: .LC_loginpage_loginInfo {
 5823: 	margin-left:20px;
 5824: 	float:left;
 5825: 	width:30%;
 5826: 	border:1px solid #CCCCCC;
 5827: 	padding:10px;
 5828: }
 5829: 
 5830: .LC_loginpage_loginDomain {
 5831: 	margin-right:20px;
 5832: 	width:20%;
 5833: 	float:left;
 5834: 	padding:10px;
 5835: }
 5836: 
 5837: .LC_loginpage_space {
 5838: 	clear:both;
 5839: 	margin-bottom:20px;
 5840: 	border-bottom: 1px solid #CCCCCC;
 5841: }
 5842: 
 5843: .LC_loginpage_fieldset{
 5844: 	border: 1px solid #CCCCCC;
 5845: 	margin: 0 auto;
 5846: }
 5847: 
 5848: .LC_loginpage_legend{
 5849: 	padding: 2px;
 5850: 	margin: 0px;
 5851: 	font-size:14px;
 5852: 	font-weight:bold;
 5853: }
 5854: 
 5855: 
 5856: END
 5857: }
 5858: 
 5859: =pod
 5860: 
 5861: =item * &headtag()
 5862: 
 5863: Returns a uniform footer for LON-CAPA web pages.
 5864: 
 5865: Inputs: $title - optional title for the head
 5866:         $head_extra - optional extra HTML to put inside the <head>
 5867:         $args - optional arguments
 5868:             force_register - if is true call registerurl so the remote is 
 5869:                              informed
 5870:             redirect       -> array ref of
 5871:                                    1- seconds before redirect occurs
 5872:                                    2- url to redirect to
 5873:                                    3- whether the side effect should occur
 5874:                            (side effect of setting 
 5875:                                $env{'internal.head.redirect'} to the url 
 5876:                                redirected too)
 5877:             domain         -> force to color decorate a page for a specific
 5878:                                domain
 5879:             function       -> force usage of a specific rolish color scheme
 5880:             bgcolor        -> override the default page bgcolor
 5881:             no_auto_mt_title
 5882:                            -> prevent &mt()ing the title arg
 5883: 
 5884: =cut
 5885: 
 5886: sub headtag {
 5887:     my ($title,$head_extra,$args) = @_;
 5888:     
 5889:     my $function = $args->{'function'} || &get_users_function();
 5890:     my $domain   = $args->{'domain'}   || &determinedomain();
 5891:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5892:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5893: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5894: 		   #time(),
 5895: 		   $env{'environment.color.timestamp'},
 5896: 		   $function,$domain,$bgcolor);
 5897: 
 5898:     $url = '/adm/css/'.&escape($url).'.css';
 5899: 
 5900:     my $result =
 5901: 	'<head>'.
 5902: 	&font_settings();
 5903: 
 5904:     if (!$args->{'frameset'}) {
 5905: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5906:     }
 5907:     if ($args->{'force_register'}) {
 5908: 	$result .= &Apache::lonmenu::registerurl(1);
 5909:     }
 5910:     if (!$args->{'no_nav_bar'} 
 5911: 	&& !$args->{'only_body'}
 5912: 	&& !$args->{'frameset'}) {
 5913: 	$result .= &help_menu_js();
 5914:     }
 5915: 
 5916:     if (ref($args->{'redirect'})) {
 5917: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5918: 	$url = &Apache::lonenc::check_encrypt($url);
 5919: 	if (!$inhibit_continue) {
 5920: 	    $env{'internal.head.redirect'} = $url;
 5921: 	}
 5922: 	$result.=<<ADDMETA
 5923: <meta http-equiv="pragma" content="no-cache" />
 5924: <meta http-equiv="Refresh" content="$time; url=$url" />
 5925: ADDMETA
 5926:     }
 5927:     if (!defined($title)) {
 5928: 	$title = 'The LearningOnline Network with CAPA';
 5929:     }
 5930:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5931:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5932: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5933: 	.$head_extra;
 5934:     return $result;
 5935: }
 5936: 
 5937: =pod
 5938: 
 5939: =item * &font_settings()
 5940: 
 5941: Returns neccessary <meta> to set the proper encoding
 5942: 
 5943: Inputs: none
 5944: 
 5945: =cut
 5946: 
 5947: sub font_settings {
 5948:     my $headerstring='';
 5949:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5950: 	$headerstring.=
 5951: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5952:     }
 5953:     return $headerstring;
 5954: }
 5955: 
 5956: =pod
 5957: 
 5958: =item * &xml_begin()
 5959: 
 5960: Returns the needed doctype and <html>
 5961: 
 5962: Inputs: none
 5963: 
 5964: =cut
 5965: 
 5966: sub xml_begin {
 5967:     my $output='';
 5968: 
 5969:     if ($env{'internal.start_page'}==1) {
 5970: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5971:     }
 5972: 
 5973:     if ($env{'browser.mathml'}) {
 5974: 	$output='<?xml version="1.0"?>'
 5975:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5976: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5977:             
 5978: #	    .'<!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">] >'
 5979: 	    .'<!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">'
 5980:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5981: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5982:     } else {
 5983: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 5984:     }
 5985:     return $output;
 5986: }
 5987: 
 5988: =pod
 5989: 
 5990: =item * &endheadtag()
 5991: 
 5992: Returns a uniform </head> for LON-CAPA web pages.
 5993: 
 5994: Inputs: none
 5995: 
 5996: =cut
 5997: 
 5998: sub endheadtag {
 5999:     return '</head>';
 6000: }
 6001: 
 6002: =pod
 6003: 
 6004: =item * &head()
 6005: 
 6006: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6007: 
 6008: Inputs:
 6009: 
 6010: =over 4
 6011: 
 6012: $title - optional title for the page
 6013: 
 6014: $head_extra - optional extra HTML to put inside the <head>
 6015: 
 6016: =back
 6017: 
 6018: =cut
 6019: 
 6020: sub head {
 6021:     my ($title,$head_extra,$args) = @_;
 6022:     return &headtag($title,$head_extra,$args).&endheadtag();
 6023: }
 6024: 
 6025: =pod
 6026: 
 6027: =item * &start_page()
 6028: 
 6029: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6030: 
 6031: Inputs:
 6032: 
 6033: =over 4
 6034: 
 6035: $title - optional title for the page
 6036: 
 6037: $head_extra - optional extra HTML to incude inside the <head>
 6038: 
 6039: $args - additional optional args supported are:
 6040: 
 6041: =over 8
 6042: 
 6043:              only_body      -> is true will set &bodytag() onlybodytag
 6044:                                     arg on
 6045:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6046:              add_entries    -> additional attributes to add to the  <body>
 6047:              domain         -> force to color decorate a page for a 
 6048:                                     specific domain
 6049:              function       -> force usage of a specific rolish color
 6050:                                     scheme
 6051:              redirect       -> see &headtag()
 6052:              bgcolor        -> override the default page bg color
 6053:              js_ready       -> return a string ready for being used in 
 6054:                                     a javascript writeln
 6055:              html_encode    -> return a string ready for being used in 
 6056:                                     a html attribute
 6057:              force_register -> if is true will turn on the &bodytag()
 6058:                                     $forcereg arg
 6059:              body_title     -> alternate text to use instead of $title
 6060:                                     in the title box that appears, this text
 6061:                                     is not auto translated like the $title is
 6062:              frameset       -> if true will start with a <frameset>
 6063:                                     rather than <body>
 6064:              no_title       -> if true the title bar won't be shown
 6065:              skip_phases    -> hash ref of 
 6066:                                     head -> skip the <html><head> generation
 6067:                                     body -> skip all <body> generation
 6068:              no_inline_link -> if true and in remote mode, don't show the 
 6069:                                     'Switch To Inline Menu' link
 6070:              no_auto_mt_title -> prevent &mt()ing the title arg
 6071:              inherit_jsmath -> when creating popup window in a page,
 6072:                                     should it have jsmath forced on by the
 6073:                                     current page
 6074: 
 6075: =back
 6076: 
 6077: =back
 6078: 
 6079: =cut
 6080: 
 6081: sub start_page {
 6082:     my ($title,$head_extra,$args) = @_;
 6083:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6084:     my %head_args;
 6085:     foreach my $arg ('redirect','force_register','domain','function',
 6086: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6087: 		     'no_auto_mt_title') {
 6088: 	if (defined($args->{$arg})) {
 6089: 	    $head_args{$arg} = $args->{$arg};
 6090: 	}
 6091:     }
 6092: 
 6093:     $env{'internal.start_page'}++;
 6094:     my $result;
 6095:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6096: 	$result.=
 6097: 	    &xml_begin().
 6098: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6099:     }
 6100:     
 6101:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6102: 	if ($args->{'frameset'}) {
 6103: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6104: 						$args->{'add_entries'});
 6105: 	    $result .= "\n<frameset $attr_string>\n";
 6106: 	} else {
 6107: 	    $result .=
 6108: 		&bodytag($title, 
 6109: 			 $args->{'function'},       $args->{'add_entries'},
 6110: 			 $args->{'only_body'},      $args->{'domain'},
 6111: 			 $args->{'force_register'}, $args->{'body_title'},
 6112: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6113: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6114: 			 $args);
 6115: 	}
 6116:     }
 6117: 
 6118:     if ($args->{'js_ready'}) {
 6119: 		$result = &js_ready($result);
 6120:     }
 6121:     if ($args->{'html_encode'}) {
 6122: 		$result = &html_encode($result);
 6123:     }
 6124: 
 6125:     if (exists($args->{'bread_crumbs'})) {
 6126:         &Apache::lonhtmlcommon::clear_breadcrumbs();
 6127:         if (ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6128:             foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6129:                 &Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6130:             }
 6131:         }
 6132:         $result .= &Apache::lonhtmlcommon::breadcrumbs();
 6133:     }
 6134: 
 6135:     return $result;
 6136: }
 6137: 
 6138: 
 6139: =pod
 6140: 
 6141: =item * &head()
 6142: 
 6143: Returns a complete </body></html> section for LON-CAPA web pages.
 6144: 
 6145: Inputs:         $args - additional optional args supported are:
 6146:                  js_ready     -> return a string ready for being used in 
 6147:                                  a javascript writeln
 6148:                  html_encode  -> return a string ready for being used in 
 6149:                                  a html attribute
 6150:                  frameset     -> if true will start with a <frameset>
 6151:                                  rather than <body>
 6152:                  dicsussion   -> if true will get discussion from
 6153:                                   lonxml::xmlend
 6154:                                  (you can pass the target and parser arguments
 6155:                                   through optional 'target' and 'parser' args
 6156:                                   to this routine)
 6157: 
 6158: =cut
 6159: 
 6160: sub end_page {
 6161:     my ($args) = @_;
 6162:     $env{'internal.end_page'}++;
 6163:     my $result;
 6164:     if ($args->{'discussion'}) {
 6165: 	my ($target,$parser);
 6166: 	if (ref($args->{'discussion'})) {
 6167: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6168: 				$args->{'discussion'}{'parser'});
 6169: 	}
 6170: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6171:     }
 6172: 
 6173:     if ($args->{'frameset'}) {
 6174: 	$result .= '</frameset>';
 6175:     } else {
 6176: 	$result .= &endbodytag($args);
 6177:     }
 6178:     $result .= "\n</html>";
 6179: 
 6180:     if ($args->{'js_ready'}) {
 6181: 	$result = &js_ready($result);
 6182:     }
 6183: 
 6184:     if ($args->{'html_encode'}) {
 6185: 	$result = &html_encode($result);
 6186:     }
 6187: 
 6188:     return $result;
 6189: }
 6190: 
 6191: sub html_encode {
 6192:     my ($result) = @_;
 6193: 
 6194:     $result = &HTML::Entities::encode($result,'<>&"');
 6195:     
 6196:     return $result;
 6197: }
 6198: sub js_ready {
 6199:     my ($result) = @_;
 6200: 
 6201:     $result =~ s/[\n\r]/ /xmsg;
 6202:     $result =~ s/\\/\\\\/xmsg;
 6203:     $result =~ s/'/\\'/xmsg;
 6204:     $result =~ s{</}{<\\/}xmsg;
 6205:     
 6206:     return $result;
 6207: }
 6208: 
 6209: sub validate_page {
 6210:     if (  exists($env{'internal.start_page'})
 6211: 	  &&     $env{'internal.start_page'} > 1) {
 6212: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6213: 				 $env{'internal.start_page'}.' '.
 6214: 				 $ENV{'request.filename'});
 6215:     }
 6216:     if (  exists($env{'internal.end_page'})
 6217: 	  &&     $env{'internal.end_page'} > 1) {
 6218: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6219: 				 $env{'internal.end_page'}.' '.
 6220: 				 $env{'request.filename'});
 6221:     }
 6222:     if (     exists($env{'internal.start_page'})
 6223: 	&& ! exists($env{'internal.end_page'})) {
 6224: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6225: 				 $env{'request.filename'});
 6226:     }
 6227:     if (   ! exists($env{'internal.start_page'})
 6228: 	&&   exists($env{'internal.end_page'})) {
 6229: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6230: 				 $env{'request.filename'});
 6231:     }
 6232: }
 6233: 
 6234: sub simple_error_page {
 6235:     my ($r,$title,$msg) = @_;
 6236:     my $page =
 6237: 	&Apache::loncommon::start_page($title).
 6238: 	&mt($msg).
 6239: 	&Apache::loncommon::end_page();
 6240:     if (ref($r)) {
 6241: 	$r->print($page);
 6242: 	return;
 6243:     }
 6244:     return $page;
 6245: }
 6246: 
 6247: {
 6248:     my @row_count;
 6249:     sub start_data_table {
 6250: 	my ($add_class) = @_;
 6251: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6252: 	unshift(@row_count,0);
 6253: 	return '<table class="'.$css_class.'">'."\n";
 6254:     }
 6255: 
 6256:     sub end_data_table {
 6257: 	shift(@row_count);
 6258: 	return '</table>'."\n";;
 6259:     }
 6260: 
 6261:     sub start_data_table_row {
 6262: 	my ($add_class) = @_;
 6263: 	$row_count[0]++;
 6264: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6265: 	$css_class = (join(' ',$css_class,$add_class));
 6266: 	return  '<tr class="'.$css_class.'">'."\n";;
 6267:     }
 6268:     
 6269:     sub continue_data_table_row {
 6270: 	my ($add_class) = @_;
 6271: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6272: 	$css_class = (join(' ',$css_class,$add_class));
 6273: 	return  '<tr class="'.$css_class.'">'."\n";;
 6274:     }
 6275: 
 6276:     sub end_data_table_row {
 6277: 	return '</tr>'."\n";;
 6278:     }
 6279: 
 6280:     sub start_data_table_empty_row {
 6281: #	$row_count[0]++;
 6282: 	return  '<tr class="LC_empty_row" >'."\n";;
 6283:     }
 6284: 
 6285:     sub end_data_table_empty_row {
 6286: 	return '</tr>'."\n";;
 6287:     }
 6288: 
 6289:     sub start_data_table_header_row {
 6290: 	return  '<tr class="LC_header_row">'."\n";;
 6291:     }
 6292: 
 6293:     sub end_data_table_header_row {
 6294: 	return '</tr>'."\n";;
 6295:     }
 6296: }
 6297: 
 6298: =pod
 6299: 
 6300: =item * &inhibit_menu_check($arg)
 6301: 
 6302: Checks for a inhibitmenu state and generates output to preserve it
 6303: 
 6304: Inputs:         $arg - can be any of
 6305:                      - undef - in which case the return value is a string 
 6306:                                to add  into arguments list of a uri
 6307:                      - 'input' - in which case the return value is a HTML
 6308:                                  <form> <input> field of type hidden to
 6309:                                  preserve the value
 6310:                      - a url - in which case the return value is the url with
 6311:                                the neccesary cgi args added to preserve the
 6312:                                inhibitmenu state
 6313:                      - a ref to a url - no return value, but the string is
 6314:                                         updated to include the neccessary cgi
 6315:                                         args to preserve the inhibitmenu state
 6316: 
 6317: =cut
 6318: 
 6319: sub inhibit_menu_check {
 6320:     my ($arg) = @_;
 6321:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6322:     if ($arg eq 'input') {
 6323: 	if ($env{'form.inhibitmenu'}) {
 6324: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6325: 	} else {
 6326: 	    return
 6327: 	}
 6328:     }
 6329:     if ($env{'form.inhibitmenu'}) {
 6330: 	if (ref($arg)) {
 6331: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6332: 	} elsif ($arg eq '') {
 6333: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6334: 	} else {
 6335: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6336: 	}
 6337:     }
 6338:     if (!ref($arg)) {
 6339: 	return $arg;
 6340:     }
 6341: }
 6342: 
 6343: ###############################################
 6344: 
 6345: =pod
 6346: 
 6347: =back
 6348: 
 6349: =head1 User Information Routines
 6350: 
 6351: =over 4
 6352: 
 6353: =item * &get_users_function()
 6354: 
 6355: Used by &bodytag to determine the current users primary role.
 6356: Returns either 'student','coordinator','admin', or 'author'.
 6357: 
 6358: =cut
 6359: 
 6360: ###############################################
 6361: sub get_users_function {
 6362:     my $function = 'student';
 6363:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6364:         $function='coordinator';
 6365:     }
 6366:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6367:         $function='admin';
 6368:     }
 6369:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6370:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6371:         $function='author';
 6372:     }
 6373:     return $function;
 6374: }
 6375: 
 6376: ###############################################
 6377: 
 6378: =pod
 6379: 
 6380: =item * &check_user_status()
 6381: 
 6382: Determines current status of supplied role for a
 6383: specific user. Roles can be active, previous or future.
 6384: 
 6385: Inputs: 
 6386: user's domain, user's username, course's domain,
 6387: course's number, optional section ID.
 6388: 
 6389: Outputs:
 6390: role status: active, previous or future. 
 6391: 
 6392: =cut
 6393: 
 6394: sub check_user_status {
 6395:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6396:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6397:     my @uroles = keys %userinfo;
 6398:     my $srchstr;
 6399:     my $active_chk = 'none';
 6400:     my $now = time;
 6401:     if (@uroles > 0) {
 6402:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6403:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6404:         } else {
 6405:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6406:         }
 6407:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6408:             my $role_end = 0;
 6409:             my $role_start = 0;
 6410:             $active_chk = 'active';
 6411:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6412:                 $role_end = $1;
 6413:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6414:                     $role_start = $1;
 6415:                 }
 6416:             }
 6417:             if ($role_start > 0) {
 6418:                 if ($now < $role_start) {
 6419:                     $active_chk = 'future';
 6420:                 }
 6421:             }
 6422:             if ($role_end > 0) {
 6423:                 if ($now > $role_end) {
 6424:                     $active_chk = 'previous';
 6425:                 }
 6426:             }
 6427:         }
 6428:     }
 6429:     return $active_chk;
 6430: }
 6431: 
 6432: ###############################################
 6433: 
 6434: =pod
 6435: 
 6436: =item * &get_sections()
 6437: 
 6438: Determines all the sections for a course including
 6439: sections with students and sections containing other roles.
 6440: Incoming parameters: 
 6441: 
 6442: 1. domain
 6443: 2. course number 
 6444: 3. reference to array containing roles for which sections should 
 6445: be gathered (optional).
 6446: 4. reference to array containing status types for which sections 
 6447: should be gathered (optional).
 6448: 
 6449: If the third argument is undefined, sections are gathered for any role. 
 6450: If the fourth argument is undefined, sections are gathered for any status.
 6451: Permissible values are 'active' or 'future' or 'previous'.
 6452:  
 6453: Returns section hash (keys are section IDs, values are
 6454: number of users in each section), subject to the
 6455: optional roles filter, optional status filter 
 6456: 
 6457: =cut
 6458: 
 6459: ###############################################
 6460: sub get_sections {
 6461:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6462:     if (!defined($cdom) || !defined($cnum)) {
 6463:         my $cid =  $env{'request.course.id'};
 6464: 
 6465: 	return if (!defined($cid));
 6466: 
 6467:         $cdom = $env{'course.'.$cid.'.domain'};
 6468:         $cnum = $env{'course.'.$cid.'.num'};
 6469:     }
 6470: 
 6471:     my %sectioncount;
 6472:     my $now = time;
 6473: 
 6474:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6475: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6476: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6477: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6478:         my $start_index = &Apache::loncoursedata::CL_START();
 6479:         my $end_index = &Apache::loncoursedata::CL_END();
 6480:         my $status;
 6481: 	while (my ($student,$data) = each(%$classlist)) {
 6482: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6483: 				                     $data->[$status_index],
 6484:                                                      $data->[$start_index],
 6485:                                                      $data->[$end_index]);
 6486:             if ($stu_status eq 'Active') {
 6487:                 $status = 'active';
 6488:             } elsif ($end < $now) {
 6489:                 $status = 'previous';
 6490:             } elsif ($start > $now) {
 6491:                 $status = 'future';
 6492:             } 
 6493: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6494:                 if ((!defined($possible_status)) || (($status ne '') && 
 6495:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6496: 		    $sectioncount{$section}++;
 6497:                 }
 6498: 	    }
 6499: 	}
 6500:     }
 6501:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6502:     foreach my $user (sort(keys(%courseroles))) {
 6503: 	if ($user !~ /^(\w{2})/) { next; }
 6504: 	my ($role) = ($user =~ /^(\w{2})/);
 6505: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6506: 	my ($section,$status);
 6507: 	if ($role eq 'cr' &&
 6508: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6509: 	    $section=$1;
 6510: 	}
 6511: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6512: 	if (!defined($section) || $section eq '-1') { next; }
 6513:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6514:         if ($end == -1 && $start == -1) {
 6515:             next; #deleted role
 6516:         }
 6517:         if (!defined($possible_status)) { 
 6518:             $sectioncount{$section}++;
 6519:         } else {
 6520:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6521:                 $status = 'active';
 6522:             } elsif ($end < $now) {
 6523:                 $status = 'future';
 6524:             } elsif ($start > $now) {
 6525:                 $status = 'previous';
 6526:             }
 6527:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6528:                 $sectioncount{$section}++;
 6529:             }
 6530:         }
 6531:     }
 6532:     return %sectioncount;
 6533: }
 6534: 
 6535: ###############################################
 6536: 
 6537: =pod
 6538: 
 6539: =item * &get_course_users()
 6540: 
 6541: Retrieves usernames:domains for users in the specified course
 6542: with specific role(s), and access status. 
 6543: 
 6544: Incoming parameters:
 6545: 1. course domain
 6546: 2. course number
 6547: 3. access status: users must have - either active, 
 6548: previous, future, or all.
 6549: 4. reference to array of permissible roles
 6550: 5. reference to array of section restrictions (optional)
 6551: 6. reference to results object (hash of hashes).
 6552: 7. reference to optional userdata hash
 6553: 8. reference to optional statushash
 6554: 9. flag if privileged users (except those set to unhide in
 6555:    course settings) should be excluded    
 6556: Keys of top level results hash are roles.
 6557: Keys of inner hashes are username:domain, with 
 6558: values set to access type.
 6559: Optional userdata hash returns an array with arguments in the 
 6560: same order as loncoursedata::get_classlist() for student data.
 6561: 
 6562: Optional statushash returns
 6563: 
 6564: Entries for end, start, section and status are blank because
 6565: of the possibility of multiple values for non-student roles.
 6566: 
 6567: =cut
 6568: 
 6569: ###############################################
 6570: 
 6571: sub get_course_users {
 6572:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6573:     my %idx = ();
 6574:     my %seclists;
 6575: 
 6576:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6577:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6578:     $idx{end} = &Apache::loncoursedata::CL_END();
 6579:     $idx{start} = &Apache::loncoursedata::CL_START();
 6580:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6581:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6582:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6583:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6584: 
 6585:     if (grep(/^st$/,@{$roles})) {
 6586:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6587:         my $now = time;
 6588:         foreach my $student (keys(%{$classlist})) {
 6589:             my $match = 0;
 6590:             my $secmatch = 0;
 6591:             my $section = $$classlist{$student}[$idx{section}];
 6592:             my $status = $$classlist{$student}[$idx{status}];
 6593:             if ($section eq '') {
 6594:                 $section = 'none';
 6595:             }
 6596:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6597:                 if (grep(/^all$/,@{$sections})) {
 6598:                     $secmatch = 1;
 6599:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6600:                     if (grep(/^none$/,@{$sections})) {
 6601:                         $secmatch = 1;
 6602:                     }
 6603:                 } else {  
 6604: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6605: 		        $secmatch = 1;
 6606:                     }
 6607: 		}
 6608:                 if (!$secmatch) {
 6609:                     next;
 6610:                 }
 6611:             }
 6612:             if (defined($$types{'active'})) {
 6613:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6614:                     push(@{$$users{st}{$student}},'active');
 6615:                     $match = 1;
 6616:                 }
 6617:             }
 6618:             if (defined($$types{'previous'})) {
 6619:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6620:                     push(@{$$users{st}{$student}},'previous');
 6621:                     $match = 1;
 6622:                 }
 6623:             }
 6624:             if (defined($$types{'future'})) {
 6625:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6626:                     push(@{$$users{st}{$student}},'future');
 6627:                     $match = 1;
 6628:                 }
 6629:             }
 6630:             if ($match) {
 6631:                 push(@{$seclists{$student}},$section);
 6632:                 if (ref($userdata) eq 'HASH') {
 6633:                     $$userdata{$student} = $$classlist{$student};
 6634:                 }
 6635:                 if (ref($statushash) eq 'HASH') {
 6636:                     $statushash->{$student}{'st'}{$section} = $status;
 6637:                 }
 6638:             }
 6639:         }
 6640:     }
 6641:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6642:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6643:         my $now = time;
 6644:         my %displaystatus = ( previous => 'Expired',
 6645:                               active   => 'Active',
 6646:                               future   => 'Future',
 6647:                             );
 6648:         my %nothide;
 6649:         if ($hidepriv) {
 6650:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6651:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6652:                 if ($user !~ /:/) {
 6653:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6654:                 } else {
 6655:                     $nothide{$user} = 1;
 6656:                 }
 6657:             }
 6658:         }
 6659:         foreach my $person (sort(keys(%coursepersonnel))) {
 6660:             my $match = 0;
 6661:             my $secmatch = 0;
 6662:             my $status;
 6663:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6664:             $user =~ s/:$//;
 6665:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6666:             if ($end == -1 || $start == -1) {
 6667:                 next;
 6668:             }
 6669:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6670:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6671:                 my ($uname,$udom) = split(/:/,$user);
 6672:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6673:                     if (grep(/^all$/,@{$sections})) {
 6674:                         $secmatch = 1;
 6675:                     } elsif ($usec eq '') {
 6676:                         if (grep(/^none$/,@{$sections})) {
 6677:                             $secmatch = 1;
 6678:                         }
 6679:                     } else {
 6680:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6681:                             $secmatch = 1;
 6682:                         }
 6683:                     }
 6684:                     if (!$secmatch) {
 6685:                         next;
 6686:                     }
 6687:                 }
 6688:                 if ($usec eq '') {
 6689:                     $usec = 'none';
 6690:                 }
 6691:                 if ($uname ne '' && $udom ne '') {
 6692:                     if ($hidepriv) {
 6693:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6694:                             (!$nothide{$uname.':'.$udom})) {
 6695:                             next;
 6696:                         }
 6697:                     }
 6698:                     if ($end > 0 && $end < $now) {
 6699:                         $status = 'previous';
 6700:                     } elsif ($start > $now) {
 6701:                         $status = 'future';
 6702:                     } else {
 6703:                         $status = 'active';
 6704:                     }
 6705:                     foreach my $type (keys(%{$types})) { 
 6706:                         if ($status eq $type) {
 6707:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6708:                                 push(@{$$users{$role}{$user}},$type);
 6709:                             }
 6710:                             $match = 1;
 6711:                         }
 6712:                     }
 6713:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6714:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6715: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6716:                         }
 6717:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6718:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6719:                         }
 6720:                         if (ref($statushash) eq 'HASH') {
 6721:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6722:                         }
 6723:                     }
 6724:                 }
 6725:             }
 6726:         }
 6727:         if (grep(/^ow$/,@{$roles})) {
 6728:             if ((defined($cdom)) && (defined($cnum))) {
 6729:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6730:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6731:                     my $owner = $csettings{'internal.courseowner'};
 6732:                     next if ($owner eq '');
 6733:                     my ($ownername,$ownerdom);
 6734:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6735:                         $ownername = $1;
 6736:                         $ownerdom = $2;
 6737:                     } else {
 6738:                         $ownername = $owner;
 6739:                         $ownerdom = $cdom;
 6740:                         $owner = $ownername.':'.$ownerdom;
 6741:                     }
 6742:                     @{$$users{'ow'}{$owner}} = 'any';
 6743:                     if (defined($userdata) && 
 6744: 			!exists($$userdata{$owner})) {
 6745: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6746:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6747:                             push(@{$seclists{$owner}},'none');
 6748:                         }
 6749:                         if (ref($statushash) eq 'HASH') {
 6750:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6751:                         }
 6752: 		    }
 6753:                 }
 6754:             }
 6755:         }
 6756:         foreach my $user (keys(%seclists)) {
 6757:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6758:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6759:         }
 6760:     }
 6761:     return;
 6762: }
 6763: 
 6764: sub get_user_info {
 6765:     my ($udom,$uname,$idx,$userdata) = @_;
 6766:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6767: 	&plainname($uname,$udom,'lastname');
 6768:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6769:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6770:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6771:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6772:     return;
 6773: }
 6774: 
 6775: ###############################################
 6776: 
 6777: =pod
 6778: 
 6779: =item * &get_user_quota()
 6780: 
 6781: Retrieves quota assigned for storage of portfolio files for a user  
 6782: 
 6783: Incoming parameters:
 6784: 1. user's username
 6785: 2. user's domain
 6786: 
 6787: Returns:
 6788: 1. Disk quota (in Mb) assigned to student.
 6789: 2. (Optional) Type of setting: custom or default
 6790:    (individually assigned or default for user's 
 6791:    institutional status).
 6792: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6793:    or student - types as defined in localenroll::inst_usertypes 
 6794:    for user's domain, which determines default quota for user.
 6795: 4. (Optional) - Default quota which would apply to the user.
 6796: 
 6797: If a value has been stored in the user's environment, 
 6798: it will return that, otherwise it returns the maximal default
 6799: defined for the user's instituional status(es) in the domain.
 6800: 
 6801: =cut
 6802: 
 6803: ###############################################
 6804: 
 6805: 
 6806: sub get_user_quota {
 6807:     my ($uname,$udom) = @_;
 6808:     my ($quota,$quotatype,$settingstatus,$defquota);
 6809:     if (!defined($udom)) {
 6810:         $udom = $env{'user.domain'};
 6811:     }
 6812:     if (!defined($uname)) {
 6813:         $uname = $env{'user.name'};
 6814:     }
 6815:     if (($udom eq '' || $uname eq '') ||
 6816:         ($udom eq 'public') && ($uname eq 'public')) {
 6817:         $quota = 0;
 6818:         $quotatype = 'default';
 6819:         $defquota = 0; 
 6820:     } else {
 6821:         my $inststatus;
 6822:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6823:             $quota = $env{'environment.portfolioquota'};
 6824:             $inststatus = $env{'environment.inststatus'};
 6825:         } else {
 6826:             my %userenv = 
 6827:                 &Apache::lonnet::get('environment',['portfolioquota',
 6828:                                      'inststatus'],$udom,$uname);
 6829:             my ($tmp) = keys(%userenv);
 6830:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6831:                 $quota = $userenv{'portfolioquota'};
 6832:                 $inststatus = $userenv{'inststatus'};
 6833:             } else {
 6834:                 undef(%userenv);
 6835:             }
 6836:         }
 6837:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6838:         if ($quota eq '') {
 6839:             $quota = $defquota;
 6840:             $quotatype = 'default';
 6841:         } else {
 6842:             $quotatype = 'custom';
 6843:         }
 6844:     }
 6845:     if (wantarray) {
 6846:         return ($quota,$quotatype,$settingstatus,$defquota);
 6847:     } else {
 6848:         return $quota;
 6849:     }
 6850: }
 6851: 
 6852: ###############################################
 6853: 
 6854: =pod
 6855: 
 6856: =item * &default_quota()
 6857: 
 6858: Retrieves default quota assigned for storage of user portfolio files,
 6859: given an (optional) user's institutional status.
 6860: 
 6861: Incoming parameters:
 6862: 1. domain
 6863: 2. (Optional) institutional status(es).  This is a : separated list of 
 6864:    status types (e.g., faculty, staff, student etc.)
 6865:    which apply to the user for whom the default is being retrieved.
 6866:    If the institutional status string in undefined, the domain
 6867:    default quota will be returned. 
 6868: 
 6869: Returns:
 6870: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6871: 2. (Optional) institutional type which determined the value of the
 6872:    default quota.
 6873: 
 6874: If a value has been stored in the domain's configuration db,
 6875: it will return that, otherwise it returns 20 (for backwards 
 6876: compatibility with domains which have not set up a configuration
 6877: db file; the original statically defined portfolio quota was 20 Mb). 
 6878: 
 6879: If the user's status includes multiple types (e.g., staff and student),
 6880: the largest default quota which applies to the user determines the
 6881: default quota returned.
 6882: 
 6883: =cut
 6884: 
 6885: ###############################################
 6886: 
 6887: 
 6888: sub default_quota {
 6889:     my ($udom,$inststatus) = @_;
 6890:     my ($defquota,$settingstatus);
 6891:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6892:                                             ['quotas'],$udom);
 6893:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6894:         if ($inststatus ne '') {
 6895:             my @statuses = split(/:/,$inststatus);
 6896:             foreach my $item (@statuses) {
 6897:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6898:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6899:                         if ($defquota eq '') {
 6900:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6901:                             $settingstatus = $item;
 6902:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6903:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6904:                             $settingstatus = $item;
 6905:                         }
 6906:                     }
 6907:                 } else {
 6908:                     if ($quotahash{'quotas'}{$item} ne '') {
 6909:                         if ($defquota eq '') {
 6910:                             $defquota = $quotahash{'quotas'}{$item};
 6911:                             $settingstatus = $item;
 6912:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6913:                             $defquota = $quotahash{'quotas'}{$item};
 6914:                             $settingstatus = $item;
 6915:                         }
 6916:                     }
 6917:                 }
 6918:             }
 6919:         }
 6920:         if ($defquota eq '') {
 6921:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6922:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 6923:             } else {
 6924:                 $defquota = $quotahash{'quotas'}{'default'};
 6925:             }
 6926:             $settingstatus = 'default';
 6927:         }
 6928:     } else {
 6929:         $settingstatus = 'default';
 6930:         $defquota = 20;
 6931:     }
 6932:     if (wantarray) {
 6933:         return ($defquota,$settingstatus);
 6934:     } else {
 6935:         return $defquota;
 6936:     }
 6937: }
 6938: 
 6939: sub get_secgrprole_info {
 6940:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6941:     my %sections_count = &get_sections($cdom,$cnum);
 6942:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6943:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6944:     my @groups = sort(keys(%curr_groups));
 6945:     my $allroles = [];
 6946:     my $rolehash;
 6947:     my $accesshash = {
 6948:                      active => 'Currently has access',
 6949:                      future => 'Will have future access',
 6950:                      previous => 'Previously had access',
 6951:                   };
 6952:     if ($needroles) {
 6953:         $rolehash = {'all' => 'all'};
 6954:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6955: 	if (&Apache::lonnet::error(%user_roles)) {
 6956: 	    undef(%user_roles);
 6957: 	}
 6958:         foreach my $item (keys(%user_roles)) {
 6959:             my ($role)=split(/\:/,$item,2);
 6960:             if ($role eq 'cr') { next; }
 6961:             if ($role =~ /^cr/) {
 6962:                 $$rolehash{$role} = (split('/',$role))[3];
 6963:             } else {
 6964:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6965:             }
 6966:         }
 6967:         foreach my $key (sort(keys(%{$rolehash}))) {
 6968:             push(@{$allroles},$key);
 6969:         }
 6970:         push (@{$allroles},'st');
 6971:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6972:     }
 6973:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6974: }
 6975: 
 6976: sub user_picker {
 6977:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6978:     my $currdom = $dom;
 6979:     my %curr_selected = (
 6980:                         srchin => 'dom',
 6981:                         srchby => 'lastname',
 6982:                       );
 6983:     my $srchterm;
 6984:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6985:         if ($srch->{'srchby'} ne '') {
 6986:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6987:         }
 6988:         if ($srch->{'srchin'} ne '') {
 6989:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6990:         }
 6991:         if ($srch->{'srchtype'} ne '') {
 6992:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6993:         }
 6994:         if ($srch->{'srchdomain'} ne '') {
 6995:             $currdom = $srch->{'srchdomain'};
 6996:         }
 6997:         $srchterm = $srch->{'srchterm'};
 6998:     }
 6999:     my %lt=&Apache::lonlocal::texthash(
 7000:                     'usr'       => 'Search criteria',
 7001:                     'doma'      => 'Domain/institution to search',
 7002:                     'uname'     => 'username',
 7003:                     'lastname'  => 'last name',
 7004:                     'lastfirst' => 'last name, first name',
 7005:                     'crs'       => 'in this course',
 7006:                     'dom'       => 'in selected LON-CAPA domain', 
 7007:                     'alc'       => 'all LON-CAPA',
 7008:                     'instd'     => 'in institutional directory for selected domain',
 7009:                     'exact'     => 'is',
 7010:                     'contains'  => 'contains',
 7011:                     'begins'    => 'begins with',
 7012:                     'youm'      => "You must include some text to search for.",
 7013:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7014:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7015:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7016:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7017:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7018:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7019:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7020:                                        );
 7021:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7022:     my $srchinsel = ' <select name="srchin">';
 7023: 
 7024:     my @srchins = ('crs','dom','alc','instd');
 7025: 
 7026:     foreach my $option (@srchins) {
 7027:         # FIXME 'alc' option unavailable until 
 7028:         #       loncreateuser::print_user_query_page()
 7029:         #       has been completed.
 7030:         next if ($option eq 'alc');
 7031:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7032:         if ($curr_selected{'srchin'} eq $option) {
 7033:             $srchinsel .= ' 
 7034:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7035:         } else {
 7036:             $srchinsel .= '
 7037:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7038:         }
 7039:     }
 7040:     $srchinsel .= "\n  </select>\n";
 7041: 
 7042:     my $srchbysel =  ' <select name="srchby">';
 7043:     foreach my $option ('lastname','lastfirst','uname') {
 7044:         if ($curr_selected{'srchby'} eq $option) {
 7045:             $srchbysel .= '
 7046:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7047:         } else {
 7048:             $srchbysel .= '
 7049:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7050:          }
 7051:     }
 7052:     $srchbysel .= "\n  </select>\n";
 7053: 
 7054:     my $srchtypesel = ' <select name="srchtype">';
 7055:     foreach my $option ('begins','contains','exact') {
 7056:         if ($curr_selected{'srchtype'} eq $option) {
 7057:             $srchtypesel .= '
 7058:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7059:         } else {
 7060:             $srchtypesel .= '
 7061:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7062:         }
 7063:     }
 7064:     $srchtypesel .= "\n  </select>\n";
 7065: 
 7066:     my ($newuserscript,$new_user_create);
 7067: 
 7068:     if ($forcenewuser) {
 7069:         if (ref($srch) eq 'HASH') {
 7070:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7071:                 if ($cancreate) {
 7072:                     $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>';
 7073:                 } else {
 7074:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7075:                     my %usertypetext = (
 7076:                         official   => 'institutional',
 7077:                         unofficial => 'non-institutional',
 7078:                     );
 7079:                     $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 />';
 7080:                 }
 7081:             }
 7082:         }
 7083: 
 7084:         $newuserscript = <<"ENDSCRIPT";
 7085: 
 7086: function setSearch(createnew,callingForm) {
 7087:     if (createnew == 1) {
 7088:         for (var i=0; i<callingForm.srchby.length; i++) {
 7089:             if (callingForm.srchby.options[i].value == 'uname') {
 7090:                 callingForm.srchby.selectedIndex = i;
 7091:             }
 7092:         }
 7093:         for (var i=0; i<callingForm.srchin.length; i++) {
 7094:             if ( callingForm.srchin.options[i].value == 'dom') {
 7095: 		callingForm.srchin.selectedIndex = i;
 7096:             }
 7097:         }
 7098:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7099:             if (callingForm.srchtype.options[i].value == 'exact') {
 7100:                 callingForm.srchtype.selectedIndex = i;
 7101:             }
 7102:         }
 7103:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7104:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7105:                 callingForm.srchdomain.selectedIndex = i;
 7106:             }
 7107:         }
 7108:     }
 7109: }
 7110: ENDSCRIPT
 7111: 
 7112:     }
 7113: 
 7114:     my $output = <<"END_BLOCK";
 7115: <script type="text/javascript">
 7116: function validateEntry(callingForm) {
 7117: 
 7118:     var checkok = 1;
 7119:     var srchin;
 7120:     for (var i=0; i<callingForm.srchin.length; i++) {
 7121: 	if ( callingForm.srchin[i].checked ) {
 7122: 	    srchin = callingForm.srchin[i].value;
 7123: 	}
 7124:     }
 7125: 
 7126:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7127:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7128:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7129:     var srchterm =  callingForm.srchterm.value;
 7130:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7131:     var msg = "";
 7132: 
 7133:     if (srchterm == "") {
 7134:         checkok = 0;
 7135:         msg += "$lt{'youm'}\\n";
 7136:     }
 7137: 
 7138:     if (srchtype== 'begins') {
 7139:         if (srchterm.length < 2) {
 7140:             checkok = 0;
 7141:             msg += "$lt{'thte'}\\n";
 7142:         }
 7143:     }
 7144: 
 7145:     if (srchtype== 'contains') {
 7146:         if (srchterm.length < 3) {
 7147:             checkok = 0;
 7148:             msg += "$lt{'thet'}\\n";
 7149:         }
 7150:     }
 7151:     if (srchin == 'instd') {
 7152:         if (srchdomain == '') {
 7153:             checkok = 0;
 7154:             msg += "$lt{'yomc'}\\n";
 7155:         }
 7156:     }
 7157:     if (srchin == 'dom') {
 7158:         if (srchdomain == '') {
 7159:             checkok = 0;
 7160:             msg += "$lt{'ymcd'}\\n";
 7161:         }
 7162:     }
 7163:     if (srchby == 'lastfirst') {
 7164:         if (srchterm.indexOf(",") == -1) {
 7165:             checkok = 0;
 7166:             msg += "$lt{'whus'}\\n";
 7167:         }
 7168:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7169:             checkok = 0;
 7170:             msg += "$lt{'whse'}\\n";
 7171:         }
 7172:     }
 7173:     if (checkok == 0) {
 7174:         alert("$lt{'thfo'}\\n"+msg);
 7175:         return;
 7176:     }
 7177:     if (checkok == 1) {
 7178:         callingForm.submit();
 7179:     }
 7180: }
 7181: 
 7182: $newuserscript
 7183: 
 7184: </script>
 7185: 
 7186: $new_user_create
 7187: 
 7188: <table>
 7189:  <tr>
 7190:   <td>$lt{'doma'}:</td>
 7191:   <td>$domform</td>
 7192:   </td>
 7193:  </tr>
 7194:  <tr>
 7195:   <td>$lt{'usr'}:</td>
 7196:   <td>$srchbysel
 7197:       $srchtypesel 
 7198:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7199:       $srchinsel 
 7200:   </td>
 7201:  </tr>
 7202: </table>
 7203: <br />
 7204: END_BLOCK
 7205: 
 7206:     return $output;
 7207: }
 7208: 
 7209: sub user_rule_check {
 7210:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7211:     my $response;
 7212:     if (ref($usershash) eq 'HASH') {
 7213:         foreach my $user (keys(%{$usershash})) {
 7214:             my ($uname,$udom) = split(/:/,$user);
 7215:             next if ($udom eq '' || $uname eq '');
 7216:             my ($id,$newuser);
 7217:             if (ref($usershash->{$user}) eq 'HASH') {
 7218:                 $newuser = $usershash->{$user}->{'newuser'};
 7219:                 $id = $usershash->{$user}->{'id'};
 7220:             }
 7221:             my $inst_response;
 7222:             if (ref($checks) eq 'HASH') {
 7223:                 if (defined($checks->{'username'})) {
 7224:                     ($inst_response,%{$inst_results->{$user}}) = 
 7225:                         &Apache::lonnet::get_instuser($udom,$uname);
 7226:                 } elsif (defined($checks->{'id'})) {
 7227:                     ($inst_response,%{$inst_results->{$user}}) =
 7228:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7229:                 }
 7230:             } else {
 7231:                 ($inst_response,%{$inst_results->{$user}}) =
 7232:                     &Apache::lonnet::get_instuser($udom,$uname);
 7233:                 return;
 7234:             }
 7235:             if (!$got_rules->{$udom}) {
 7236:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7237:                                                   ['usercreation'],$udom);
 7238:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7239:                     foreach my $item ('username','id') {
 7240:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7241:                             $$curr_rules{$udom}{$item} = 
 7242:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7243:                         }
 7244:                     }
 7245:                 }
 7246:                 $got_rules->{$udom} = 1;  
 7247:             }
 7248:             foreach my $item (keys(%{$checks})) {
 7249:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7250:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7251:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7252:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7253:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7254:                                 if ($rule_check{$rule}) {
 7255:                                     $$rulematch{$user}{$item} = $rule;
 7256:                                     if ($inst_response eq 'ok') {
 7257:                                         if (ref($inst_results) eq 'HASH') {
 7258:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7259:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7260:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7261:                                                 }
 7262:                                             }
 7263:                                         }
 7264:                                     }
 7265:                                     last;
 7266:                                 }
 7267:                             }
 7268:                         }
 7269:                     }
 7270:                 }
 7271:             }
 7272:         }
 7273:     }
 7274:     return;
 7275: }
 7276: 
 7277: sub user_rule_formats {
 7278:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7279:     my %text = ( 
 7280:                  'username' => 'Usernames',
 7281:                  'id'       => 'IDs',
 7282:                );
 7283:     my $output;
 7284:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7285:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7286:         if (@{$ruleorder} > 0) {
 7287:             $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>';
 7288:             foreach my $rule (@{$ruleorder}) {
 7289:                 if (ref($curr_rules) eq 'ARRAY') {
 7290:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7291:                         if (ref($rules->{$rule}) eq 'HASH') {
 7292:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7293:                                         $rules->{$rule}{'desc'}.'</li>';
 7294:                         }
 7295:                     }
 7296:                 }
 7297:             }
 7298:             $output .= '</ul>';
 7299:         }
 7300:     }
 7301:     return $output;
 7302: }
 7303: 
 7304: sub instrule_disallow_msg {
 7305:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7306:     my $response;
 7307:     my %text = (
 7308:                   item   => 'username',
 7309:                   items  => 'usernames',
 7310:                   match  => 'matches',
 7311:                   do     => 'does',
 7312:                   action => 'a username',
 7313:                   one    => 'one',
 7314:                );
 7315:     if ($count > 1) {
 7316:         $text{'item'} = 'usernames';
 7317:         $text{'match'} ='match';
 7318:         $text{'do'} = 'do';
 7319:         $text{'action'} = 'usernames',
 7320:         $text{'one'} = 'ones';
 7321:     }
 7322:     if ($checkitem eq 'id') {
 7323:         $text{'items'} = 'IDs';
 7324:         $text{'item'} = 'ID';
 7325:         $text{'action'} = 'an ID';
 7326:         if ($count > 1) {
 7327:             $text{'item'} = 'IDs';
 7328:             $text{'action'} = 'IDs';
 7329:         }
 7330:     }
 7331:     $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 />';
 7332:     if ($mode eq 'upload') {
 7333:         if ($checkitem eq 'username') {
 7334:             $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'}.");
 7335:         } elsif ($checkitem eq 'id') {
 7336:             $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.");
 7337:         }
 7338:     } elsif ($mode eq 'selfcreate') {
 7339:         if ($checkitem eq 'id') {
 7340:             $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.");
 7341:         }
 7342:     } else {
 7343:         if ($checkitem eq 'username') {
 7344:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7345:         } elsif ($checkitem eq 'id') {
 7346:             $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.");
 7347:         }
 7348:     }
 7349:     return $response;
 7350: }
 7351: 
 7352: sub personal_data_fieldtitles {
 7353:     my %fieldtitles = &Apache::lonlocal::texthash (
 7354:                         id => 'Student/Employee ID',
 7355:                         permanentemail => 'E-mail address',
 7356:                         lastname => 'Last Name',
 7357:                         firstname => 'First Name',
 7358:                         middlename => 'Middle Name',
 7359:                         generation => 'Generation',
 7360:                         gen => 'Generation',
 7361:                    );
 7362:     return %fieldtitles;
 7363: }
 7364: 
 7365: sub sorted_inst_types {
 7366:     my ($dom) = @_;
 7367:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7368:     my $othertitle = &mt('All users');
 7369:     if ($env{'request.course.id'}) {
 7370:         $othertitle  = &mt('Any users');
 7371:     }
 7372:     my @types;
 7373:     if (ref($order) eq 'ARRAY') {
 7374:         @types = @{$order};
 7375:     }
 7376:     if (@types == 0) {
 7377:         if (ref($usertypes) eq 'HASH') {
 7378:             @types = sort(keys(%{$usertypes}));
 7379:         }
 7380:     }
 7381:     if (keys(%{$usertypes}) > 0) {
 7382:         $othertitle = &mt('Other users');
 7383:     }
 7384:     return ($othertitle,$usertypes,\@types);
 7385: }
 7386: 
 7387: sub get_institutional_codes {
 7388:     my ($settings,$allcourses,$LC_code) = @_;
 7389: # Get complete list of course sections to update
 7390:     my @currsections = ();
 7391:     my @currxlists = ();
 7392:     my $coursecode = $$settings{'internal.coursecode'};
 7393: 
 7394:     if ($$settings{'internal.sectionnums'} ne '') {
 7395:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7396:     }
 7397: 
 7398:     if ($$settings{'internal.crosslistings'} ne '') {
 7399:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7400:     }
 7401: 
 7402:     if (@currxlists > 0) {
 7403:         foreach (@currxlists) {
 7404:             if (m/^([^:]+):(\w*)$/) {
 7405:                 unless (grep/^$1$/,@{$allcourses}) {
 7406:                     push @{$allcourses},$1;
 7407:                     $$LC_code{$1} = $2;
 7408:                 }
 7409:             }
 7410:         }
 7411:     }
 7412:  
 7413:     if (@currsections > 0) {
 7414:         foreach (@currsections) {
 7415:             if (m/^(\w+):(\w*)$/) {
 7416:                 my $sec = $coursecode.$1;
 7417:                 my $lc_sec = $2;
 7418:                 unless (grep/^$sec$/,@{$allcourses}) {
 7419:                     push @{$allcourses},$sec;
 7420:                     $$LC_code{$sec} = $lc_sec;
 7421:                 }
 7422:             }
 7423:         }
 7424:     }
 7425:     return;
 7426: }
 7427: 
 7428: =pod
 7429: 
 7430: =back
 7431: 
 7432: =head1 HTTP Helpers
 7433: 
 7434: =over 4
 7435: 
 7436: =item * &get_unprocessed_cgi($query,$possible_names)
 7437: 
 7438: Modify the %env hash to contain unprocessed CGI form parameters held in
 7439: $query.  The parameters listed in $possible_names (an array reference),
 7440: will be set in $env{'form.name'} if they do not already exist.
 7441: 
 7442: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7443: $possible_names is an ref to an array of form element names.  As an example:
 7444: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7445: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7446: 
 7447: =cut
 7448: 
 7449: sub get_unprocessed_cgi {
 7450:   my ($query,$possible_names)= @_;
 7451:   # $Apache::lonxml::debug=1;
 7452:   foreach my $pair (split(/&/,$query)) {
 7453:     my ($name, $value) = split(/=/,$pair);
 7454:     $name = &unescape($name);
 7455:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7456:       $value =~ tr/+/ /;
 7457:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7458:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7459:     }
 7460:   }
 7461: }
 7462: 
 7463: =pod
 7464: 
 7465: =item * &cacheheader() 
 7466: 
 7467: returns cache-controlling header code
 7468: 
 7469: =cut
 7470: 
 7471: sub cacheheader {
 7472:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7473:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7474:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7475:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7476:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7477:     return $output;
 7478: }
 7479: 
 7480: =pod
 7481: 
 7482: =item * &no_cache($r) 
 7483: 
 7484: specifies header code to not have cache
 7485: 
 7486: =cut
 7487: 
 7488: sub no_cache {
 7489:     my ($r) = @_;
 7490:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7491: 	$env{'request.method'} ne 'GET') { return ''; }
 7492:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7493:     $r->no_cache(1);
 7494:     $r->header_out("Expires" => $date);
 7495:     $r->header_out("Pragma" => "no-cache");
 7496: }
 7497: 
 7498: sub content_type {
 7499:     my ($r,$type,$charset) = @_;
 7500:     if ($r) {
 7501: 	#  Note that printout.pl calls this with undef for $r.
 7502: 	&no_cache($r);
 7503:     }
 7504:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7505:     unless ($charset) {
 7506: 	$charset=&Apache::lonlocal::current_encoding;
 7507:     }
 7508:     if ($charset) { $type.='; charset='.$charset; }
 7509:     if ($r) {
 7510: 	$r->content_type($type);
 7511:     } else {
 7512: 	print("Content-type: $type\n\n");
 7513:     }
 7514: }
 7515: 
 7516: =pod
 7517: 
 7518: =item * &add_to_env($name,$value) 
 7519: 
 7520: adds $name to the %env hash with value
 7521: $value, if $name already exists, the entry is converted to an array
 7522: reference and $value is added to the array.
 7523: 
 7524: =cut
 7525: 
 7526: sub add_to_env {
 7527:   my ($name,$value)=@_;
 7528:   if (defined($env{$name})) {
 7529:     if (ref($env{$name})) {
 7530:       #already have multiple values
 7531:       push(@{ $env{$name} },$value);
 7532:     } else {
 7533:       #first time seeing multiple values, convert hash entry to an arrayref
 7534:       my $first=$env{$name};
 7535:       undef($env{$name});
 7536:       push(@{ $env{$name} },$first,$value);
 7537:     }
 7538:   } else {
 7539:     $env{$name}=$value;
 7540:   }
 7541: }
 7542: 
 7543: =pod
 7544: 
 7545: =item * &get_env_multiple($name) 
 7546: 
 7547: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7548: values may be defined and end up as an array ref.
 7549: 
 7550: returns an array of values
 7551: 
 7552: =cut
 7553: 
 7554: sub get_env_multiple {
 7555:     my ($name) = @_;
 7556:     my @values;
 7557:     if (defined($env{$name})) {
 7558:         # exists is it an array
 7559:         if (ref($env{$name})) {
 7560:             @values=@{ $env{$name} };
 7561:         } else {
 7562:             $values[0]=$env{$name};
 7563:         }
 7564:     }
 7565:     return(@values);
 7566: }
 7567: 
 7568: sub ask_for_embedded_content {
 7569:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7570:     my $upload_output = '
 7571:    <form name="upload_embedded" action="'.$actionurl.'"
 7572:                   method="post" enctype="multipart/form-data">';
 7573:     $upload_output .= $state;
 7574:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7575: 
 7576:     my $num = 0;
 7577:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7578:         $upload_output .= &start_data_table_row().
 7579:             '<td>'.$embed_file.'</td><td>';
 7580:         if ($args->{'ignore_remote_references'}
 7581:             && $embed_file =~ m{^\w+://}) {
 7582:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7583:         } elsif ($args->{'error_on_invalid_names'}
 7584:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7585: 
 7586:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7587: 
 7588:         } else {
 7589:             $upload_output .='
 7590:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7591:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7592:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7593:             $upload_output .=
 7594:                 "\n\t\t".
 7595:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7596:                 $attrib.'" />';
 7597:             if (exists($$codebase{$embed_file})) {
 7598:                 $upload_output .=
 7599:                     "\n\t\t".
 7600:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7601:                     &escape($$codebase{$embed_file}).'" />';
 7602:             }
 7603:         }
 7604:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7605:         $num++;
 7606:     }
 7607:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7608:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7609:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7610:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7611:    </form>';
 7612:     return $upload_output;
 7613: }
 7614: 
 7615: sub upload_embedded {
 7616:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7617:         $current_disk_usage) = @_;
 7618:     my $output;
 7619:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7620:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7621:         my $orig_uploaded_filename =
 7622:             $env{'form.embedded_item_'.$i.'.filename'};
 7623: 
 7624:         $env{'form.embedded_orig_'.$i} =
 7625:             &unescape($env{'form.embedded_orig_'.$i});
 7626:         my ($path,$fname) =
 7627:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7628:         # no path, whole string is fname
 7629:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7630: 
 7631:         $path = $env{'form.currentpath'}.$path;
 7632:         $fname = &Apache::lonnet::clean_filename($fname);
 7633:         # See if there is anything left
 7634:         next if ($fname eq '');
 7635: 
 7636:         # Check if file already exists as a file or directory.
 7637:         my ($state,$msg);
 7638:         if ($context eq 'portfolio') {
 7639:             my $port_path = $dirpath;
 7640:             if ($group ne '') {
 7641:                 $port_path = "groups/$group/$port_path";
 7642:             }
 7643:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7644:                                               $dir_root,$port_path,$disk_quota,
 7645:                                               $current_disk_usage,$uname,$udom);
 7646:             if ($state eq 'will_exceed_quota'
 7647:                 || $state eq 'file_locked'
 7648:                 || $state eq 'file_exists' ) {
 7649:                 $output .= $msg;
 7650:                 next;
 7651:             }
 7652:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7653:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7654:             if ($state eq 'exists') {
 7655:                 $output .= $msg;
 7656:                 next;
 7657:             }
 7658:         }
 7659:         # Check if extension is valid
 7660:         if (($fname =~ /\.(\w+)$/) &&
 7661:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7662:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7663:             next;
 7664:         } elsif (($fname =~ /\.(\w+)$/) &&
 7665:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7666:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7667:             next;
 7668:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7669:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7670:             next;
 7671:         }
 7672: 
 7673:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7674:         if ($context eq 'portfolio') {
 7675:             my $result=
 7676:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7677:                                                 $dirpath.$path);
 7678:             if ($result !~ m|^/uploaded/|) {
 7679:                 $output .= '<span class="LC_error">'
 7680:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7681:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7682:                       .'</span><br />';
 7683:                 next;
 7684:             } else {
 7685:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7686:                            $path.$fname.'</span>').'</p>';     
 7687:             }
 7688:         } else {
 7689: # Save the file
 7690:             my $target = $env{'form.embedded_item_'.$i};
 7691:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7692:             my $dest = $fullpath.$fname;
 7693:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7694:             my @parts=split(/\//,$fullpath);
 7695:             my $count;
 7696:             my $filepath = $dir_root;
 7697:             for ($count=4;$count<=$#parts;$count++) {
 7698:                 $filepath .= "/$parts[$count]";
 7699:                 if ((-e $filepath)!=1) {
 7700:                     mkdir($filepath,0770);
 7701:                 }
 7702:             }
 7703:             my $fh;
 7704:             if (!open($fh,'>'.$dest)) {
 7705:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7706:                 $output .= '<span class="LC_error">'.
 7707:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7708:                            '</span><br />';
 7709:             } else {
 7710:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7711:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7712:                     $output .= '<span class="LC_error">'.
 7713:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7714:                               '</span><br />';
 7715:                 } else {
 7716:                     if ($context eq 'testbank') {
 7717:                         $output .= &mt('Embedded file uploaded successfully:').
 7718:                                    '&nbsp;<a href="'.$url.'">'.
 7719:                                    $orig_uploaded_filename.'</a><br />';
 7720:                     } else {
 7721:                         $output .= '<span class=\"LC_fontsize_large\">'.
 7722:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7723:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 7724:                     }
 7725:                 }
 7726:                 close($fh);
 7727:             }
 7728:         }
 7729:     }
 7730:     return $output;
 7731: }
 7732: 
 7733: sub check_for_existing {
 7734:     my ($path,$fname,$element) = @_;
 7735:     my ($state,$msg);
 7736:     if (-d $path.'/'.$fname) {
 7737:         $state = 'exists';
 7738:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7739:     } elsif (-e $path.'/'.$fname) {
 7740:         $state = 'exists';
 7741:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7742:     }
 7743:     if ($state eq 'exists') {
 7744:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7745:     }
 7746:     return ($state,$msg);
 7747: }
 7748: 
 7749: sub check_for_upload {
 7750:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7751:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7752:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7753:     my $getpropath = 1;
 7754:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7755:                                             $getpropath);
 7756:     my $found_file = 0;
 7757:     my $locked_file = 0;
 7758:     foreach my $line (@dir_list) {
 7759:         my ($file_name)=split(/\&/,$line,2);
 7760:         if ($file_name eq $fname){
 7761:             $file_name = $path.$file_name;
 7762:             if ($group ne '') {
 7763:                 $file_name = $group.$file_name;
 7764:             }
 7765:             $found_file = 1;
 7766:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7767:                 $locked_file = 1;
 7768:             }
 7769:         }
 7770:     }
 7771:     if (($current_disk_usage + $filesize) > $disk_quota){
 7772:         my $msg = '<span class="LC_error">'.
 7773:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7774:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7775:         return ('will_exceed_quota',$msg);
 7776:     } elsif ($found_file) {
 7777:         if ($locked_file) {
 7778:             my $msg = '<span class="LC_error">';
 7779:             $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>');
 7780:             $msg .= '</span><br />';
 7781:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7782:             return ('file_locked',$msg);
 7783:         } else {
 7784:             my $msg = '<span class="LC_error">';
 7785:             $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'});
 7786:             $msg .= '</span>';
 7787:             $msg .= '<br />';
 7788:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7789:             return ('file_exists',$msg);
 7790:         }
 7791:     }
 7792: }
 7793: 
 7794: 
 7795: =pod
 7796: 
 7797: =back
 7798: 
 7799: =head1 CSV Upload/Handling functions
 7800: 
 7801: =over 4
 7802: 
 7803: =item * &upfile_store($r)
 7804: 
 7805: Store uploaded file, $r should be the HTTP Request object,
 7806: needs $env{'form.upfile'}
 7807: returns $datatoken to be put into hidden field
 7808: 
 7809: =cut
 7810: 
 7811: sub upfile_store {
 7812:     my $r=shift;
 7813:     $env{'form.upfile'}=~s/\r/\n/gs;
 7814:     $env{'form.upfile'}=~s/\f/\n/gs;
 7815:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7816:     $env{'form.upfile'}=~s/\n+$//gs;
 7817: 
 7818:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7819: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7820:     {
 7821:         my $datafile = $r->dir_config('lonDaemons').
 7822:                            '/tmp/'.$datatoken.'.tmp';
 7823:         if ( open(my $fh,">$datafile") ) {
 7824:             print $fh $env{'form.upfile'};
 7825:             close($fh);
 7826:         }
 7827:     }
 7828:     return $datatoken;
 7829: }
 7830: 
 7831: =pod
 7832: 
 7833: =item * &load_tmp_file($r)
 7834: 
 7835: Load uploaded file from tmp, $r should be the HTTP Request object,
 7836: needs $env{'form.datatoken'},
 7837: sets $env{'form.upfile'} to the contents of the file
 7838: 
 7839: =cut
 7840: 
 7841: sub load_tmp_file {
 7842:     my $r=shift;
 7843:     my @studentdata=();
 7844:     {
 7845:         my $studentfile = $r->dir_config('lonDaemons').
 7846:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7847:         if ( open(my $fh,"<$studentfile") ) {
 7848:             @studentdata=<$fh>;
 7849:             close($fh);
 7850:         }
 7851:     }
 7852:     $env{'form.upfile'}=join('',@studentdata);
 7853: }
 7854: 
 7855: =pod
 7856: 
 7857: =item * &upfile_record_sep()
 7858: 
 7859: Separate uploaded file into records
 7860: returns array of records,
 7861: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7862: 
 7863: =cut
 7864: 
 7865: sub upfile_record_sep {
 7866:     if ($env{'form.upfiletype'} eq 'xml') {
 7867:     } else {
 7868: 	my @records;
 7869: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7870: 	    if ($line=~/^\s*$/) { next; }
 7871: 	    push(@records,$line);
 7872: 	}
 7873: 	return @records;
 7874:     }
 7875: }
 7876: 
 7877: =pod
 7878: 
 7879: =item * &record_sep($record)
 7880: 
 7881: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7882: 
 7883: =cut
 7884: 
 7885: sub takeleft {
 7886:     my $index=shift;
 7887:     return substr('0000'.$index,-4,4);
 7888: }
 7889: 
 7890: sub record_sep {
 7891:     my $record=shift;
 7892:     my %components=();
 7893:     if ($env{'form.upfiletype'} eq 'xml') {
 7894:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7895:         my $i=0;
 7896:         foreach my $field (split(/\s+/,$record)) {
 7897:             $field=~s/^(\"|\')//;
 7898:             $field=~s/(\"|\')$//;
 7899:             $components{&takeleft($i)}=$field;
 7900:             $i++;
 7901:         }
 7902:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7903:         my $i=0;
 7904:         foreach my $field (split(/\t/,$record)) {
 7905:             $field=~s/^(\"|\')//;
 7906:             $field=~s/(\"|\')$//;
 7907:             $components{&takeleft($i)}=$field;
 7908:             $i++;
 7909:         }
 7910:     } else {
 7911:         my $separator=',';
 7912:         if ($env{'form.upfiletype'} eq 'semisv') {
 7913:             $separator=';';
 7914:         }
 7915:         my $i=0;
 7916: # the character we are looking for to indicate the end of a quote or a record 
 7917:         my $looking_for=$separator;
 7918: # do not add the characters to the fields
 7919:         my $ignore=0;
 7920: # we just encountered a separator (or the beginning of the record)
 7921:         my $just_found_separator=1;
 7922: # store the field we are working on here
 7923:         my $field='';
 7924: # work our way through all characters in record
 7925:         foreach my $character ($record=~/(.)/g) {
 7926:             if ($character eq $looking_for) {
 7927:                if ($character ne $separator) {
 7928: # Found the end of a quote, again looking for separator
 7929:                   $looking_for=$separator;
 7930:                   $ignore=1;
 7931:                } else {
 7932: # Found a separator, store away what we got
 7933:                   $components{&takeleft($i)}=$field;
 7934: 	          $i++;
 7935:                   $just_found_separator=1;
 7936:                   $ignore=0;
 7937:                   $field='';
 7938:                }
 7939:                next;
 7940:             }
 7941: # single or double quotation marks after a separator indicate beginning of a quote
 7942: # we are now looking for the end of the quote and need to ignore separators
 7943:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7944:                $looking_for=$character;
 7945:                next;
 7946:             }
 7947: # ignore would be true after we reached the end of a quote
 7948:             if ($ignore) { next; }
 7949:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7950:             $field.=$character;
 7951:             $just_found_separator=0; 
 7952:         }
 7953: # catch the very last entry, since we never encountered the separator
 7954:         $components{&takeleft($i)}=$field;
 7955:     }
 7956:     return %components;
 7957: }
 7958: 
 7959: ######################################################
 7960: ######################################################
 7961: 
 7962: =pod
 7963: 
 7964: =item * &upfile_select_html()
 7965: 
 7966: Return HTML code to select a file from the users machine and specify 
 7967: the file type.
 7968: 
 7969: =cut
 7970: 
 7971: ######################################################
 7972: ######################################################
 7973: sub upfile_select_html {
 7974:     my %Types = (
 7975:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7976:                  semisv => &mt('Semicolon separated values'),
 7977:                  space => &mt('Space separated'),
 7978:                  tab   => &mt('Tabulator separated'),
 7979: #                 xml   => &mt('HTML/XML'),
 7980:                  );
 7981:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7982:         '<br />'.&mt('Type').': <select name="upfiletype">';
 7983:     foreach my $type (sort(keys(%Types))) {
 7984:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7985:     }
 7986:     $Str .= "</select>\n";
 7987:     return $Str;
 7988: }
 7989: 
 7990: sub get_samples {
 7991:     my ($records,$toget) = @_;
 7992:     my @samples=({});
 7993:     my $got=0;
 7994:     foreach my $rec (@$records) {
 7995: 	my %temp = &record_sep($rec);
 7996: 	if (! grep(/\S/, values(%temp))) { next; }
 7997: 	if (%temp) {
 7998: 	    $samples[$got]=\%temp;
 7999: 	    $got++;
 8000: 	    if ($got == $toget) { last; }
 8001: 	}
 8002:     }
 8003:     return \@samples;
 8004: }
 8005: 
 8006: ######################################################
 8007: ######################################################
 8008: 
 8009: =pod
 8010: 
 8011: =item * &csv_print_samples($r,$records)
 8012: 
 8013: Prints a table of sample values from each column uploaded $r is an
 8014: Apache Request ref, $records is an arrayref from
 8015: &Apache::loncommon::upfile_record_sep
 8016: 
 8017: =cut
 8018: 
 8019: ######################################################
 8020: ######################################################
 8021: sub csv_print_samples {
 8022:     my ($r,$records) = @_;
 8023:     my $samples = &get_samples($records,5);
 8024: 
 8025:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8026:               &start_data_table_header_row());
 8027:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8028:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8029:     $r->print(&end_data_table_header_row());
 8030:     foreach my $hash (@$samples) {
 8031: 	$r->print(&start_data_table_row());
 8032: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8033: 	    $r->print('<td>');
 8034: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8035: 	    $r->print('</td>');
 8036: 	}
 8037: 	$r->print(&end_data_table_row());
 8038:     }
 8039:     $r->print(&end_data_table().'<br />'."\n");
 8040: }
 8041: 
 8042: ######################################################
 8043: ######################################################
 8044: 
 8045: =pod
 8046: 
 8047: =item * &csv_print_select_table($r,$records,$d)
 8048: 
 8049: Prints a table to create associations between values and table columns.
 8050: 
 8051: $r is an Apache Request ref,
 8052: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8053: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8054: 
 8055: =cut
 8056: 
 8057: ######################################################
 8058: ######################################################
 8059: sub csv_print_select_table {
 8060:     my ($r,$records,$d) = @_;
 8061:     my $i=0;
 8062:     my $samples = &get_samples($records,1);
 8063:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8064: 	      &start_data_table().&start_data_table_header_row().
 8065:               '<th>'.&mt('Attribute').'</th>'.
 8066:               '<th>'.&mt('Column').'</th>'.
 8067:               &end_data_table_header_row()."\n");
 8068:     foreach my $array_ref (@$d) {
 8069: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8070: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8071: 
 8072: 	$r->print('<td><select name=f'.$i.
 8073: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8074: 	$r->print('<option value="none"></option>');
 8075: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8076: 	    $r->print('<option value="'.$sample.'"'.
 8077:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8078:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8079: 	}
 8080: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8081: 	$i++;
 8082:     }
 8083:     $r->print(&end_data_table());
 8084:     $i--;
 8085:     return $i;
 8086: }
 8087: 
 8088: ######################################################
 8089: ######################################################
 8090: 
 8091: =pod
 8092: 
 8093: =item * &csv_samples_select_table($r,$records,$d)
 8094: 
 8095: Prints a table of sample values from the upload and can make associate samples to internal names.
 8096: 
 8097: $r is an Apache Request ref,
 8098: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8099: $d is an array of 2 element arrays (internal name, displayed name)
 8100: 
 8101: =cut
 8102: 
 8103: ######################################################
 8104: ######################################################
 8105: sub csv_samples_select_table {
 8106:     my ($r,$records,$d) = @_;
 8107:     my $i=0;
 8108:     #
 8109:     my $max_samples = 5;
 8110:     my $samples = &get_samples($records,$max_samples);
 8111:     $r->print(&start_data_table().
 8112:               &start_data_table_header_row().'<th>'.
 8113:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8114:               &end_data_table_header_row());
 8115: 
 8116:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8117: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8118: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8119: 	foreach my $option (@$d) {
 8120: 	    my ($value,$display,$defaultcol)=@{ $option };
 8121: 	    $r->print('<option value="'.$value.'"'.
 8122:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8123:                       $display.'</option>');
 8124: 	}
 8125: 	$r->print('</select></td><td>');
 8126: 	foreach my $line (0..($max_samples-1)) {
 8127: 	    if (defined($samples->[$line]{$key})) { 
 8128: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8129: 	    }
 8130: 	}
 8131: 	$r->print('</td>'.&end_data_table_row());
 8132: 	$i++;
 8133:     }
 8134:     $r->print(&end_data_table());
 8135:     $i--;
 8136:     return($i);
 8137: }
 8138: 
 8139: ######################################################
 8140: ######################################################
 8141: 
 8142: =pod
 8143: 
 8144: =item * &clean_excel_name($name)
 8145: 
 8146: Returns a replacement for $name which does not contain any illegal characters.
 8147: 
 8148: =cut
 8149: 
 8150: ######################################################
 8151: ######################################################
 8152: sub clean_excel_name {
 8153:     my ($name) = @_;
 8154:     $name =~ s/[:\*\?\/\\]//g;
 8155:     if (length($name) > 31) {
 8156:         $name = substr($name,0,31);
 8157:     }
 8158:     return $name;
 8159: }
 8160: 
 8161: =pod
 8162: 
 8163: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8164: 
 8165: Returns either 1 or undef
 8166: 
 8167: 1 if the part is to be hidden, undef if it is to be shown
 8168: 
 8169: Arguments are:
 8170: 
 8171: $id the id of the part to be checked
 8172: $symb, optional the symb of the resource to check
 8173: $udom, optional the domain of the user to check for
 8174: $uname, optional the username of the user to check for
 8175: 
 8176: =cut
 8177: 
 8178: sub check_if_partid_hidden {
 8179:     my ($id,$symb,$udom,$uname) = @_;
 8180:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8181: 					 $symb,$udom,$uname);
 8182:     my $truth=1;
 8183:     #if the string starts with !, then the list is the list to show not hide
 8184:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8185:     my @hiddenlist=split(/,/,$hiddenparts);
 8186:     foreach my $checkid (@hiddenlist) {
 8187: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8188:     }
 8189:     return !$truth;
 8190: }
 8191: 
 8192: 
 8193: ############################################################
 8194: ############################################################
 8195: 
 8196: =pod
 8197: 
 8198: =back 
 8199: 
 8200: =head1 cgi-bin script and graphing routines
 8201: 
 8202: =over 4
 8203: 
 8204: =item * &get_cgi_id()
 8205: 
 8206: Inputs: none
 8207: 
 8208: Returns an id which can be used to pass environment variables
 8209: to various cgi-bin scripts.  These environment variables will
 8210: be removed from the users environment after a given time by
 8211: the routine &Apache::lonnet::transfer_profile_to_env.
 8212: 
 8213: =cut
 8214: 
 8215: ############################################################
 8216: ############################################################
 8217: my $uniq=0;
 8218: sub get_cgi_id {
 8219:     $uniq=($uniq+1)%100000;
 8220:     return (time.'_'.$$.'_'.$uniq);
 8221: }
 8222: 
 8223: ############################################################
 8224: ############################################################
 8225: 
 8226: =pod
 8227: 
 8228: =item * &DrawBarGraph()
 8229: 
 8230: Facilitates the plotting of data in a (stacked) bar graph.
 8231: Puts plot definition data into the users environment in order for 
 8232: graph.png to plot it.  Returns an <img> tag for the plot.
 8233: The bars on the plot are labeled '1','2',...,'n'.
 8234: 
 8235: Inputs:
 8236: 
 8237: =over 4
 8238: 
 8239: =item $Title: string, the title of the plot
 8240: 
 8241: =item $xlabel: string, text describing the X-axis of the plot
 8242: 
 8243: =item $ylabel: string, text describing the Y-axis of the plot
 8244: 
 8245: =item $Max: scalar, the maximum Y value to use in the plot
 8246: If $Max is < any data point, the graph will not be rendered.
 8247: 
 8248: =item $colors: array ref holding the colors to be used for the data sets when
 8249: they are plotted.  If undefined, default values will be used.
 8250: 
 8251: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8252: 
 8253: =item @Values: An array of array references.  Each array reference holds data
 8254: to be plotted in a stacked bar chart.
 8255: 
 8256: =item If the final element of @Values is a hash reference the key/value
 8257: pairs will be added to the graph definition.
 8258: 
 8259: =back
 8260: 
 8261: Returns:
 8262: 
 8263: An <img> tag which references graph.png and the appropriate identifying
 8264: information for the plot.
 8265: 
 8266: =cut
 8267: 
 8268: ############################################################
 8269: ############################################################
 8270: sub DrawBarGraph {
 8271:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8272:     #
 8273:     if (! defined($colors)) {
 8274:         $colors = ['#33ff00', 
 8275:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8276:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8277:                   ]; 
 8278:     }
 8279:     my $extra_settings = {};
 8280:     if (ref($Values[-1]) eq 'HASH') {
 8281:         $extra_settings = pop(@Values);
 8282:     }
 8283:     #
 8284:     my $identifier = &get_cgi_id();
 8285:     my $id = 'cgi.'.$identifier;        
 8286:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8287:         return '';
 8288:     }
 8289:     #
 8290:     my @Labels;
 8291:     if (defined($labels)) {
 8292:         @Labels = @$labels;
 8293:     } else {
 8294:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8295:             push (@Labels,$i+1);
 8296:         }
 8297:     }
 8298:     #
 8299:     my $NumBars = scalar(@{$Values[0]});
 8300:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8301:     my %ValuesHash;
 8302:     my $NumSets=1;
 8303:     foreach my $array (@Values) {
 8304:         next if (! ref($array));
 8305:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8306:             join(',',@$array);
 8307:     }
 8308:     #
 8309:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8310:     if ($NumBars < 3) {
 8311:         $width = 120+$NumBars*32;
 8312:         $xskip = 1;
 8313:         $bar_width = 30;
 8314:     } elsif ($NumBars < 5) {
 8315:         $width = 120+$NumBars*20;
 8316:         $xskip = 1;
 8317:         $bar_width = 20;
 8318:     } elsif ($NumBars < 10) {
 8319:         $width = 120+$NumBars*15;
 8320:         $xskip = 1;
 8321:         $bar_width = 15;
 8322:     } elsif ($NumBars <= 25) {
 8323:         $width = 120+$NumBars*11;
 8324:         $xskip = 5;
 8325:         $bar_width = 8;
 8326:     } elsif ($NumBars <= 50) {
 8327:         $width = 120+$NumBars*8;
 8328:         $xskip = 5;
 8329:         $bar_width = 4;
 8330:     } else {
 8331:         $width = 120+$NumBars*8;
 8332:         $xskip = 5;
 8333:         $bar_width = 4;
 8334:     }
 8335:     #
 8336:     $Max = 1 if ($Max < 1);
 8337:     if ( int($Max) < $Max ) {
 8338:         $Max++;
 8339:         $Max = int($Max);
 8340:     }
 8341:     $Title  = '' if (! defined($Title));
 8342:     $xlabel = '' if (! defined($xlabel));
 8343:     $ylabel = '' if (! defined($ylabel));
 8344:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8345:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8346:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8347:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8348:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8349:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8350:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8351:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8352:     $ValuesHash{$id.'.height'}   = $height;
 8353:     $ValuesHash{$id.'.width'}    = $width;
 8354:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8355:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8356:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8357:     #
 8358:     # Deal with other parameters
 8359:     while (my ($key,$value) = each(%$extra_settings)) {
 8360:         $ValuesHash{$id.'.'.$key} = $value;
 8361:     }
 8362:     #
 8363:     &Apache::lonnet::appenv(\%ValuesHash);
 8364:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8365: }
 8366: 
 8367: ############################################################
 8368: ############################################################
 8369: 
 8370: =pod
 8371: 
 8372: =item * &DrawXYGraph()
 8373: 
 8374: Facilitates the plotting of data in an XY graph.
 8375: Puts plot definition data into the users environment in order for 
 8376: graph.png to plot it.  Returns an <img> tag for the plot.
 8377: 
 8378: Inputs:
 8379: 
 8380: =over 4
 8381: 
 8382: =item $Title: string, the title of the plot
 8383: 
 8384: =item $xlabel: string, text describing the X-axis of the plot
 8385: 
 8386: =item $ylabel: string, text describing the Y-axis of the plot
 8387: 
 8388: =item $Max: scalar, the maximum Y value to use in the plot
 8389: If $Max is < any data point, the graph will not be rendered.
 8390: 
 8391: =item $colors: Array ref containing the hex color codes for the data to be 
 8392: plotted in.  If undefined, default values will be used.
 8393: 
 8394: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8395: 
 8396: =item $Ydata: Array ref containing Array refs.  
 8397: Each of the contained arrays will be plotted as a separate curve.
 8398: 
 8399: =item %Values: hash indicating or overriding any default values which are 
 8400: passed to graph.png.  
 8401: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8402: 
 8403: =back
 8404: 
 8405: Returns:
 8406: 
 8407: An <img> tag which references graph.png and the appropriate identifying
 8408: information for the plot.
 8409: 
 8410: =cut
 8411: 
 8412: ############################################################
 8413: ############################################################
 8414: sub DrawXYGraph {
 8415:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8416:     #
 8417:     # Create the identifier for the graph
 8418:     my $identifier = &get_cgi_id();
 8419:     my $id = 'cgi.'.$identifier;
 8420:     #
 8421:     $Title  = '' if (! defined($Title));
 8422:     $xlabel = '' if (! defined($xlabel));
 8423:     $ylabel = '' if (! defined($ylabel));
 8424:     my %ValuesHash = 
 8425:         (
 8426:          $id.'.title'  => &escape($Title),
 8427:          $id.'.xlabel' => &escape($xlabel),
 8428:          $id.'.ylabel' => &escape($ylabel),
 8429:          $id.'.y_max_value'=> $Max,
 8430:          $id.'.labels'     => join(',',@$Xlabels),
 8431:          $id.'.PlotType'   => 'XY',
 8432:          );
 8433:     #
 8434:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8435:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8436:     }
 8437:     #
 8438:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8439:         return '';
 8440:     }
 8441:     my $NumSets=1;
 8442:     foreach my $array (@{$Ydata}){
 8443:         next if (! ref($array));
 8444:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8445:     }
 8446:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8447:     #
 8448:     # Deal with other parameters
 8449:     while (my ($key,$value) = each(%Values)) {
 8450:         $ValuesHash{$id.'.'.$key} = $value;
 8451:     }
 8452:     #
 8453:     &Apache::lonnet::appenv(\%ValuesHash);
 8454:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8455: }
 8456: 
 8457: ############################################################
 8458: ############################################################
 8459: 
 8460: =pod
 8461: 
 8462: =item * &DrawXYYGraph()
 8463: 
 8464: Facilitates the plotting of data in an XY graph with two Y axes.
 8465: Puts plot definition data into the users environment in order for 
 8466: graph.png to plot it.  Returns an <img> tag for the plot.
 8467: 
 8468: Inputs:
 8469: 
 8470: =over 4
 8471: 
 8472: =item $Title: string, the title of the plot
 8473: 
 8474: =item $xlabel: string, text describing the X-axis of the plot
 8475: 
 8476: =item $ylabel: string, text describing the Y-axis of the plot
 8477: 
 8478: =item $colors: Array ref containing the hex color codes for the data to be 
 8479: plotted in.  If undefined, default values will be used.
 8480: 
 8481: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8482: 
 8483: =item $Ydata1: The first data set
 8484: 
 8485: =item $Min1: The minimum value of the left Y-axis
 8486: 
 8487: =item $Max1: The maximum value of the left Y-axis
 8488: 
 8489: =item $Ydata2: The second data set
 8490: 
 8491: =item $Min2: The minimum value of the right Y-axis
 8492: 
 8493: =item $Max2: The maximum value of the left Y-axis
 8494: 
 8495: =item %Values: hash indicating or overriding any default values which are 
 8496: passed to graph.png.  
 8497: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8498: 
 8499: =back
 8500: 
 8501: Returns:
 8502: 
 8503: An <img> tag which references graph.png and the appropriate identifying
 8504: information for the plot.
 8505: 
 8506: =cut
 8507: 
 8508: ############################################################
 8509: ############################################################
 8510: sub DrawXYYGraph {
 8511:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8512:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8513:     #
 8514:     # Create the identifier for the graph
 8515:     my $identifier = &get_cgi_id();
 8516:     my $id = 'cgi.'.$identifier;
 8517:     #
 8518:     $Title  = '' if (! defined($Title));
 8519:     $xlabel = '' if (! defined($xlabel));
 8520:     $ylabel = '' if (! defined($ylabel));
 8521:     my %ValuesHash = 
 8522:         (
 8523:          $id.'.title'  => &escape($Title),
 8524:          $id.'.xlabel' => &escape($xlabel),
 8525:          $id.'.ylabel' => &escape($ylabel),
 8526:          $id.'.labels' => join(',',@$Xlabels),
 8527:          $id.'.PlotType' => 'XY',
 8528:          $id.'.NumSets' => 2,
 8529:          $id.'.two_axes' => 1,
 8530:          $id.'.y1_max_value' => $Max1,
 8531:          $id.'.y1_min_value' => $Min1,
 8532:          $id.'.y2_max_value' => $Max2,
 8533:          $id.'.y2_min_value' => $Min2,
 8534:          );
 8535:     #
 8536:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8537:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8538:     }
 8539:     #
 8540:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8541:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8542:         return '';
 8543:     }
 8544:     my $NumSets=1;
 8545:     foreach my $array ($Ydata1,$Ydata2){
 8546:         next if (! ref($array));
 8547:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8548:     }
 8549:     #
 8550:     # Deal with other parameters
 8551:     while (my ($key,$value) = each(%Values)) {
 8552:         $ValuesHash{$id.'.'.$key} = $value;
 8553:     }
 8554:     #
 8555:     &Apache::lonnet::appenv(\%ValuesHash);
 8556:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8557: }
 8558: 
 8559: ############################################################
 8560: ############################################################
 8561: 
 8562: =pod
 8563: 
 8564: =back 
 8565: 
 8566: =head1 Statistics helper routines?  
 8567: 
 8568: Bad place for them but what the hell.
 8569: 
 8570: =over 4
 8571: 
 8572: =item * &chartlink()
 8573: 
 8574: Returns a link to the chart for a specific student.  
 8575: 
 8576: Inputs:
 8577: 
 8578: =over 4
 8579: 
 8580: =item $linktext: The text of the link
 8581: 
 8582: =item $sname: The students username
 8583: 
 8584: =item $sdomain: The students domain
 8585: 
 8586: =back
 8587: 
 8588: =back
 8589: 
 8590: =cut
 8591: 
 8592: ############################################################
 8593: ############################################################
 8594: sub chartlink {
 8595:     my ($linktext, $sname, $sdomain) = @_;
 8596:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8597:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8598:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8599:        '">'.$linktext.'</a>';
 8600: }
 8601: 
 8602: #######################################################
 8603: #######################################################
 8604: 
 8605: =pod
 8606: 
 8607: =head1 Course Environment Routines
 8608: 
 8609: =over 4
 8610: 
 8611: =item * &restore_course_settings()
 8612: 
 8613: =item * &store_course_settings()
 8614: 
 8615: Restores/Store indicated form parameters from the course environment.
 8616: Will not overwrite existing values of the form parameters.
 8617: 
 8618: Inputs: 
 8619: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8620: 
 8621: a hash ref describing the data to be stored.  For example:
 8622:    
 8623: %Save_Parameters = ('Status' => 'scalar',
 8624:     'chartoutputmode' => 'scalar',
 8625:     'chartoutputdata' => 'scalar',
 8626:     'Section' => 'array',
 8627:     'Group' => 'array',
 8628:     'StudentData' => 'array',
 8629:     'Maps' => 'array');
 8630: 
 8631: Returns: both routines return nothing
 8632: 
 8633: =back
 8634: 
 8635: =cut
 8636: 
 8637: #######################################################
 8638: #######################################################
 8639: sub store_course_settings {
 8640:     return &store_settings($env{'request.course.id'},@_);
 8641: }
 8642: 
 8643: sub store_settings {
 8644:     # save to the environment
 8645:     # appenv the same items, just to be safe
 8646:     my $udom  = $env{'user.domain'};
 8647:     my $uname = $env{'user.name'};
 8648:     my ($context,$prefix,$Settings) = @_;
 8649:     my %SaveHash;
 8650:     my %AppHash;
 8651:     while (my ($setting,$type) = each(%$Settings)) {
 8652:         my $basename = join('.','internal',$context,$prefix,$setting);
 8653:         my $envname = 'environment.'.$basename;
 8654:         if (exists($env{'form.'.$setting})) {
 8655:             # Save this value away
 8656:             if ($type eq 'scalar' &&
 8657:                 (! exists($env{$envname}) || 
 8658:                  $env{$envname} ne $env{'form.'.$setting})) {
 8659:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8660:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8661:             } elsif ($type eq 'array') {
 8662:                 my $stored_form;
 8663:                 if (ref($env{'form.'.$setting})) {
 8664:                     $stored_form = join(',',
 8665:                                         map {
 8666:                                             &escape($_);
 8667:                                         } sort(@{$env{'form.'.$setting}}));
 8668:                 } else {
 8669:                     $stored_form = 
 8670:                         &escape($env{'form.'.$setting});
 8671:                 }
 8672:                 # Determine if the array contents are the same.
 8673:                 if ($stored_form ne $env{$envname}) {
 8674:                     $SaveHash{$basename} = $stored_form;
 8675:                     $AppHash{$envname}   = $stored_form;
 8676:                 }
 8677:             }
 8678:         }
 8679:     }
 8680:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8681:                                           $udom,$uname);
 8682:     if ($put_result !~ /^(ok|delayed)/) {
 8683:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8684:                                  'got error:'.$put_result);
 8685:     }
 8686:     # Make sure these settings stick around in this session, too
 8687:     &Apache::lonnet::appenv(\%AppHash);
 8688:     return;
 8689: }
 8690: 
 8691: sub restore_course_settings {
 8692:     return &restore_settings($env{'request.course.id'},@_);
 8693: }
 8694: 
 8695: sub restore_settings {
 8696:     my ($context,$prefix,$Settings) = @_;
 8697:     while (my ($setting,$type) = each(%$Settings)) {
 8698:         next if (exists($env{'form.'.$setting}));
 8699:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8700:             '.'.$setting;
 8701:         if (exists($env{$envname})) {
 8702:             if ($type eq 'scalar') {
 8703:                 $env{'form.'.$setting} = $env{$envname};
 8704:             } elsif ($type eq 'array') {
 8705:                 $env{'form.'.$setting} = [ 
 8706:                                            map { 
 8707:                                                &unescape($_); 
 8708:                                            } split(',',$env{$envname})
 8709:                                            ];
 8710:             }
 8711:         }
 8712:     }
 8713: }
 8714: 
 8715: #######################################################
 8716: #######################################################
 8717: 
 8718: =pod
 8719: 
 8720: =head1 Domain E-mail Routines  
 8721: 
 8722: =over 4
 8723: 
 8724: =item * &build_recipient_list()
 8725: 
 8726: Build recipient lists for three types of e-mail:
 8727: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
 8728: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
 8729: 
 8730: Inputs:
 8731: defmail (scalar - email address of default recipient), 
 8732: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8733: defdom (domain for which to retrieve configuration settings),
 8734: origmail (scalar - email address of recipient from loncapa.conf, 
 8735: i.e., predates configuration by DC via domainprefs.pm 
 8736: 
 8737: Returns: comma separated list of addresses to which to send e-mail.
 8738: 
 8739: =back
 8740: 
 8741: =cut
 8742: 
 8743: ############################################################
 8744: ############################################################
 8745: sub build_recipient_list {
 8746:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8747:     my @recipients;
 8748:     my $otheremails;
 8749:     my %domconfig =
 8750:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8751:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8752:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8753:             my @contacts = ('adminemail','supportemail');
 8754:             foreach my $item (@contacts) {
 8755:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
 8756:                     my $addr = $domconfig{'contacts'}{$item}; 
 8757:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
 8758:                         push(@recipients,$addr);
 8759:                     }
 8760:                 }
 8761:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8762:             }
 8763:         }
 8764:     } elsif ($origmail ne '') {
 8765:         push(@recipients,$origmail);
 8766:     }
 8767:     if (defined($defmail)) {
 8768:         if ($defmail ne '') {
 8769:             push(@recipients,$defmail);
 8770:         }
 8771:     }
 8772:     if ($otheremails) {
 8773:         my @others;
 8774:         if ($otheremails =~ /,/) {
 8775:             @others = split(/,/,$otheremails);
 8776:         } else {
 8777:             push(@others,$otheremails);
 8778:         }
 8779:         foreach my $addr (@others) {
 8780:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8781:                 push(@recipients,$addr);
 8782:             }
 8783:         }
 8784:     }
 8785:     my $recipientlist = join(',',@recipients); 
 8786:     return $recipientlist;
 8787: }
 8788: 
 8789: ############################################################
 8790: ############################################################
 8791: 
 8792: =pod
 8793: 
 8794: =head1 Course Catalog Routines
 8795: 
 8796: =over 4
 8797: 
 8798: =item * &gather_categories()
 8799: 
 8800: Converts category definitions - keys of categories hash stored in  
 8801: coursecategories in configuration.db on the primary library server in a 
 8802: domain - to an array.  Also generates javascript and idx hash used to 
 8803: generate Domain Coordinator interface for editing Course Categories.
 8804: 
 8805: Inputs:
 8806: 
 8807: categories (reference to hash of category definitions).
 8808: 
 8809: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8810:       categories and subcategories).
 8811: 
 8812: idx (reference to hash of counters used in Domain Coordinator interface for 
 8813:       editing Course Categories).
 8814: 
 8815: jsarray (reference to array of categories used to create Javascript arrays for
 8816:          Domain Coordinator interface for editing Course Categories).
 8817: 
 8818: Returns: nothing
 8819: 
 8820: Side effects: populates cats, idx and jsarray. 
 8821: 
 8822: =cut
 8823: 
 8824: sub gather_categories {
 8825:     my ($categories,$cats,$idx,$jsarray) = @_;
 8826:     my %counters;
 8827:     my $num = 0;
 8828:     foreach my $item (keys(%{$categories})) {
 8829:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8830:         if ($container eq '' && $depth == 0) {
 8831:             $cats->[$depth][$categories->{$item}] = $cat;
 8832:         } else {
 8833:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8834:         }
 8835:         my ($escitem,$tail) = split(/:/,$item,2);
 8836:         if ($counters{$tail} eq '') {
 8837:             $counters{$tail} = $num;
 8838:             $num ++;
 8839:         }
 8840:         if (ref($idx) eq 'HASH') {
 8841:             $idx->{$item} = $counters{$tail};
 8842:         }
 8843:         if (ref($jsarray) eq 'ARRAY') {
 8844:             push(@{$jsarray->[$counters{$tail}]},$item);
 8845:         }
 8846:     }
 8847:     return;
 8848: }
 8849: 
 8850: =pod
 8851: 
 8852: =item * &extract_categories()
 8853: 
 8854: Used to generate breadcrumb trails for course categories.
 8855: 
 8856: Inputs:
 8857: 
 8858: categories (reference to hash of category definitions).
 8859: 
 8860: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8861:       categories and subcategories).
 8862: 
 8863: trails (reference to array of breacrumb trails for each category).
 8864: 
 8865: allitems (reference to hash - key is category key 
 8866:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8867: 
 8868: idx (reference to hash of counters used in Domain Coordinator interface for
 8869:       editing Course Categories).
 8870: 
 8871: jsarray (reference to array of categories used to create Javascript arrays for
 8872:          Domain Coordinator interface for editing Course Categories).
 8873: 
 8874: subcats (reference to hash of arrays containing all subcategories within each 
 8875:          category, -recursive)
 8876: 
 8877: Returns: nothing
 8878: 
 8879: Side effects: populates trails and allitems hash references.
 8880: 
 8881: =cut
 8882: 
 8883: sub extract_categories {
 8884:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8885:     if (ref($categories) eq 'HASH') {
 8886:         &gather_categories($categories,$cats,$idx,$jsarray);
 8887:         if (ref($cats->[0]) eq 'ARRAY') {
 8888:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8889:                 my $name = $cats->[0][$i];
 8890:                 my $item = &escape($name).'::0';
 8891:                 my $trailstr;
 8892:                 if ($name eq 'instcode') {
 8893:                     $trailstr = &mt('Official courses (with institutional codes)');
 8894:                 } else {
 8895:                     $trailstr = $name;
 8896:                 }
 8897:                 if ($allitems->{$item} eq '') {
 8898:                     push(@{$trails},$trailstr);
 8899:                     $allitems->{$item} = scalar(@{$trails})-1;
 8900:                 }
 8901:                 my @parents = ($name);
 8902:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8903:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8904:                         my $category = $cats->[1]{$name}[$j];
 8905:                         if (ref($subcats) eq 'HASH') {
 8906:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8907:                         }
 8908:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8909:                     }
 8910:                 } else {
 8911:                     if (ref($subcats) eq 'HASH') {
 8912:                         $subcats->{$item} = [];
 8913:                     }
 8914:                 }
 8915:             }
 8916:         }
 8917:     }
 8918:     return;
 8919: }
 8920: 
 8921: =pod
 8922: 
 8923: =item *&recurse_categories()
 8924: 
 8925: Recursively used to generate breadcrumb trails for course categories.
 8926: 
 8927: Inputs:
 8928: 
 8929: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8930:       categories and subcategories).
 8931: 
 8932: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8933: 
 8934: category (current course category, for which breadcrumb trail is being generated).
 8935: 
 8936: trails (reference to array of breadcrumb trails for each category).
 8937: 
 8938: allitems (reference to hash - key is category key
 8939:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8940: 
 8941: parents (array containing containers directories for current category, 
 8942:          back to top level). 
 8943: 
 8944: Returns: nothing
 8945: 
 8946: Side effects: populates trails and allitems hash references
 8947: 
 8948: =cut
 8949: 
 8950: sub recurse_categories {
 8951:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8952:     my $shallower = $depth - 1;
 8953:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8954:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8955:             my $name = $cats->[$depth]{$category}[$k];
 8956:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8957:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8958:             if ($allitems->{$item} eq '') {
 8959:                 push(@{$trails},$trailstr);
 8960:                 $allitems->{$item} = scalar(@{$trails})-1;
 8961:             }
 8962:             my $deeper = $depth+1;
 8963:             push(@{$parents},$category);
 8964:             if (ref($subcats) eq 'HASH') {
 8965:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 8966:                 for (my $j=@{$parents}; $j>=0; $j--) {
 8967:                     my $higher;
 8968:                     if ($j > 0) {
 8969:                         $higher = &escape($parents->[$j]).':'.
 8970:                                   &escape($parents->[$j-1]).':'.$j;
 8971:                     } else {
 8972:                         $higher = &escape($parents->[$j]).'::'.$j;
 8973:                     }
 8974:                     push(@{$subcats->{$higher}},$subcat);
 8975:                 }
 8976:             }
 8977:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 8978:                                 $subcats);
 8979:             pop(@{$parents});
 8980:         }
 8981:     } else {
 8982:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8983:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8984:         if ($allitems->{$item} eq '') {
 8985:             push(@{$trails},$trailstr);
 8986:             $allitems->{$item} = scalar(@{$trails})-1;
 8987:         }
 8988:     }
 8989:     return;
 8990: }
 8991: 
 8992: =pod
 8993: 
 8994: =item *&assign_categories_table()
 8995: 
 8996: Create a datatable for display of hierarchical categories in a domain,
 8997: with checkboxes to allow a course to be categorized. 
 8998: 
 8999: Inputs:
 9000: 
 9001: cathash - reference to hash of categories defined for the domain (from
 9002:           configuration.db)
 9003: 
 9004: currcat - scalar with an & separated list of categories assigned to a course. 
 9005: 
 9006: Returns: $output (markup to be displayed) 
 9007: 
 9008: =cut
 9009: 
 9010: sub assign_categories_table {
 9011:     my ($cathash,$currcat) = @_;
 9012:     my $output;
 9013:     if (ref($cathash) eq 'HASH') {
 9014:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9015:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9016:         $maxdepth = scalar(@cats);
 9017:         if (@cats > 0) {
 9018:             my $itemcount = 0;
 9019:             if (ref($cats[0]) eq 'ARRAY') {
 9020:                 $output = &Apache::loncommon::start_data_table();
 9021:                 my @currcategories;
 9022:                 if ($currcat ne '') {
 9023:                     @currcategories = split('&',$currcat);
 9024:                 }
 9025:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9026:                     my $parent = $cats[0][$i];
 9027:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9028:                     next if ($parent eq 'instcode');
 9029:                     my $item = &escape($parent).'::0';
 9030:                     my $checked = '';
 9031:                     if (@currcategories > 0) {
 9032:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9033:                             $checked = ' checked="checked" ';
 9034:                         }
 9035:                     }
 9036:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9037:                                '<input type="checkbox" name="usecategory" value="'.
 9038:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9039:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9040:                     my $depth = 1;
 9041:                     push(@path,$parent);
 9042:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9043:                     pop(@path);
 9044:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9045:                     $itemcount ++;
 9046:                 }
 9047:                 $output .= &Apache::loncommon::end_data_table();
 9048:             }
 9049:         }
 9050:     }
 9051:     return $output;
 9052: }
 9053: 
 9054: =pod
 9055: 
 9056: =item *&assign_category_rows()
 9057: 
 9058: Create a datatable row for display of nested categories in a domain,
 9059: with checkboxes to allow a course to be categorized,called recursively.
 9060: 
 9061: Inputs:
 9062: 
 9063: itemcount - track row number for alternating colors
 9064: 
 9065: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9066:       categories and subcategories.
 9067: 
 9068: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9069: 
 9070: parent - parent of current category item
 9071: 
 9072: path - Array containing all categories back up through the hierarchy from the
 9073:        current category to the top level.
 9074: 
 9075: currcategories - reference to array of current categories assigned to the course
 9076: 
 9077: Returns: $output (markup to be displayed).
 9078: 
 9079: =cut
 9080: 
 9081: sub assign_category_rows {
 9082:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9083:     my ($text,$name,$item,$chgstr);
 9084:     if (ref($cats) eq 'ARRAY') {
 9085:         my $maxdepth = scalar(@{$cats});
 9086:         if (ref($cats->[$depth]) eq 'HASH') {
 9087:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9088:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9089:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9090:                 $text .= '<td><table class="LC_datatable">';
 9091:                 for (my $j=0; $j<$numchildren; $j++) {
 9092:                     $name = $cats->[$depth]{$parent}[$j];
 9093:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9094:                     my $deeper = $depth+1;
 9095:                     my $checked = '';
 9096:                     if (ref($currcategories) eq 'ARRAY') {
 9097:                         if (@{$currcategories} > 0) {
 9098:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9099:                                 $checked = ' checked="checked" ';
 9100:                             }
 9101:                         }
 9102:                     }
 9103:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9104:                              '<input type="checkbox" name="usecategory" value="'.
 9105:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9106:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9107:                              '</td><td>';
 9108:                     if (ref($path) eq 'ARRAY') {
 9109:                         push(@{$path},$name);
 9110:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9111:                         pop(@{$path});
 9112:                     }
 9113:                     $text .= '</td></tr>';
 9114:                 }
 9115:                 $text .= '</table></td>';
 9116:             }
 9117:         }
 9118:     }
 9119:     return $text;
 9120: }
 9121: 
 9122: ############################################################
 9123: ############################################################
 9124: 
 9125: 
 9126: sub commit_customrole {
 9127:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9128:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9129:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9130:                          ($end?', ending '.localtime($end):'').': <b>'.
 9131:               &Apache::lonnet::assigncustomrole(
 9132:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9133:                  '</b><br />';
 9134:     return $output;
 9135: }
 9136: 
 9137: sub commit_standardrole {
 9138:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9139:     my ($output,$logmsg,$linefeed);
 9140:     if ($context eq 'auto') {
 9141:         $linefeed = "\n";
 9142:     } else {
 9143:         $linefeed = "<br />\n";
 9144:     }  
 9145:     if ($three eq 'st') {
 9146:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9147:                                          $one,$two,$sec,$context);
 9148:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9149:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9150:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9151:         } else {
 9152:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9153:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9154:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9155:             if ($context eq 'auto') {
 9156:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9157:             } else {
 9158:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9159:                &mt('Add to classlist').': <b>ok</b>';
 9160:             }
 9161:             $output .= $linefeed;
 9162:         }
 9163:     } else {
 9164:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9165:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9166:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9167:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9168:         if ($context eq 'auto') {
 9169:             $output .= $result.$linefeed;
 9170:         } else {
 9171:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9172:         }
 9173:     }
 9174:     return $output;
 9175: }
 9176: 
 9177: sub commit_studentrole {
 9178:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9179:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9180:     if ($context eq 'auto') {
 9181:         $linefeed = "\n";
 9182:     } else {
 9183:         $linefeed = '<br />'."\n";
 9184:     }
 9185:     if (defined($one) && defined($two)) {
 9186:         my $cid=$one.'_'.$two;
 9187:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9188:         my $secchange = 0;
 9189:         my $expire_role_result;
 9190:         my $modify_section_result;
 9191:         if ($oldsec ne '-1') { 
 9192:             if ($oldsec ne $sec) {
 9193:                 $secchange = 1;
 9194:                 my $now = time;
 9195:                 my $uurl='/'.$cid;
 9196:                 $uurl=~s/\_/\//g;
 9197:                 if ($oldsec) {
 9198:                     $uurl.='/'.$oldsec;
 9199:                 }
 9200:                 $oldsecurl = $uurl;
 9201:                 $expire_role_result = 
 9202:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9203:                 if ($env{'request.course.sec'} ne '') { 
 9204:                     if ($expire_role_result eq 'refused') {
 9205:                         my @roles = ('st');
 9206:                         my @statuses = ('previous');
 9207:                         my @roledoms = ($one);
 9208:                         my $withsec = 1;
 9209:                         my %roleshash = 
 9210:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9211:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9212:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9213:                             my ($oldstart,$oldend) = 
 9214:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9215:                             if ($oldend > 0 && $oldend <= $now) {
 9216:                                 $expire_role_result = 'ok';
 9217:                             }
 9218:                         }
 9219:                     }
 9220:                 }
 9221:                 $result = $expire_role_result;
 9222:             }
 9223:         }
 9224:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9225:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9226:             if ($modify_section_result =~ /^ok/) {
 9227:                 if ($secchange == 1) {
 9228:                     if ($sec eq '') {
 9229:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9230:                     } else {
 9231:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9232:                     }
 9233:                 } elsif ($oldsec eq '-1') {
 9234:                     if ($sec eq '') {
 9235:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9236:                     } else {
 9237:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9238:                     }
 9239:                 } else {
 9240:                     if ($sec eq '') {
 9241:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9242:                     } else {
 9243:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9244:                     }
 9245:                 }
 9246:             } else {
 9247:                 if ($secchange) {       
 9248:                     $$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;
 9249:                 } else {
 9250:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9251:                 }
 9252:             }
 9253:             $result = $modify_section_result;
 9254:         } elsif ($secchange == 1) {
 9255:             if ($oldsec eq '') {
 9256:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9257:             } else {
 9258:                 $$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;
 9259:             }
 9260:             if ($expire_role_result eq 'refused') {
 9261:                 my $newsecurl = '/'.$cid;
 9262:                 $newsecurl =~ s/\_/\//g;
 9263:                 if ($sec ne '') {
 9264:                     $newsecurl.='/'.$sec;
 9265:                 }
 9266:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9267:                     if ($sec eq '') {
 9268:                         $$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;
 9269:                     } else {
 9270:                         $$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;
 9271:                     }
 9272:                 }
 9273:             }
 9274:         }
 9275:     } else {
 9276:         $$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;
 9277:         $result = "error: incomplete course id\n";
 9278:     }
 9279:     return $result;
 9280: }
 9281: 
 9282: ############################################################
 9283: ############################################################
 9284: 
 9285: sub check_clone {
 9286:     my ($args,$linefeed) = @_;
 9287:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9288:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9289:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9290:     my $clonemsg;
 9291:     my $can_clone = 0;
 9292: 
 9293:     if ($clonehome eq 'no_host') {
 9294:         $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'});     
 9295:     } else {
 9296: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9297: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9298: 	    $can_clone = 1;
 9299: 	} else {
 9300: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9301: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9302: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9303:             if (grep(/^\*$/,@cloners)) {
 9304:                 $can_clone = 1;
 9305:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9306:                 $can_clone = 1;
 9307:             } else {
 9308: 	        my %roleshash =
 9309: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9310: 					 $args->{'ccdomain'},
 9311:                                          'userroles',['active'],['cc'],
 9312: 					 [$args->{'clonedomain'}]);
 9313: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9314: 		    $can_clone = 1;
 9315: 	        } else {
 9316:                     $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'});
 9317: 	        }
 9318: 	    }
 9319:         }
 9320:     }
 9321:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9322: }
 9323: 
 9324: sub construct_course {
 9325:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9326:     my $outcome;
 9327:     my $linefeed =  '<br />'."\n";
 9328:     if ($context eq 'auto') {
 9329:         $linefeed = "\n";
 9330:     }
 9331: 
 9332: #
 9333: # Are we cloning?
 9334: #
 9335:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9336:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9337: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9338: 	if ($context ne 'auto') {
 9339:             if ($clonemsg ne '') {
 9340: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9341:             }
 9342: 	}
 9343: 	$outcome .= $clonemsg.$linefeed;
 9344: 
 9345:         if (!$can_clone) {
 9346: 	    return (0,$outcome);
 9347: 	}
 9348:     }
 9349: 
 9350: #
 9351: # Open course
 9352: #
 9353:     my $crstype = lc($args->{'crstype'});
 9354:     my %cenv=();
 9355:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9356:                                              $args->{'cdescr'},
 9357:                                              $args->{'curl'},
 9358:                                              $args->{'course_home'},
 9359:                                              $args->{'nonstandard'},
 9360:                                              $args->{'crscode'},
 9361:                                              $args->{'ccuname'}.':'.
 9362:                                              $args->{'ccdomain'},
 9363:                                              $args->{'crstype'});
 9364: 
 9365:     # Note: The testing routines depend on this being output; see 
 9366:     # Utils::Course. This needs to at least be output as a comment
 9367:     # if anyone ever decides to not show this, and Utils::Course::new
 9368:     # will need to be suitably modified.
 9369:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9370: #
 9371: # Check if created correctly
 9372: #
 9373:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9374:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9375:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9376: 
 9377: #
 9378: # Do the cloning
 9379: #   
 9380:     if ($can_clone && $cloneid) {
 9381: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9382: 	if ($context ne 'auto') {
 9383: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9384: 	}
 9385: 	$outcome .= $clonemsg.$linefeed;
 9386: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9387: # Copy all files
 9388: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9389: # Restore URL
 9390: 	$cenv{'url'}=$oldcenv{'url'};
 9391: # Restore title
 9392: 	$cenv{'description'}=$oldcenv{'description'};
 9393: # Mark as cloned
 9394: 	$cenv{'clonedfrom'}=$cloneid;
 9395: # Need to clone grading mode
 9396:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9397:         $cenv{'grading'}=$newenv{'grading'};
 9398: # Do not clone these environment entries
 9399:         &Apache::lonnet::del('environment',
 9400:                   ['default_enrollment_start_date',
 9401:                    'default_enrollment_end_date',
 9402:                    'question.email',
 9403:                    'policy.email',
 9404:                    'comment.email',
 9405:                    'pch.users.denied',
 9406:                    'plc.users.denied',
 9407:                    'hidefromcat',
 9408:                    'categories'],
 9409:                    $$crsudom,$$crsunum);
 9410:     }
 9411: 
 9412: #
 9413: # Set environment (will override cloned, if existing)
 9414: #
 9415:     my @sections = ();
 9416:     my @xlists = ();
 9417:     if ($args->{'crstype'}) {
 9418:         $cenv{'type'}=$args->{'crstype'};
 9419:     }
 9420:     if ($args->{'crsid'}) {
 9421:         $cenv{'courseid'}=$args->{'crsid'};
 9422:     }
 9423:     if ($args->{'crscode'}) {
 9424:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9425:     }
 9426:     if ($args->{'crsquota'} ne '') {
 9427:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9428:     } else {
 9429:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9430:     }
 9431:     if ($args->{'ccuname'}) {
 9432:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9433:                                         ':'.$args->{'ccdomain'};
 9434:     } else {
 9435:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9436:     }
 9437:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9438:     if ($args->{'crssections'}) {
 9439:         $cenv{'internal.sectionnums'} = '';
 9440:         if ($args->{'crssections'} =~ m/,/) {
 9441:             @sections = split/,/,$args->{'crssections'};
 9442:         } else {
 9443:             $sections[0] = $args->{'crssections'};
 9444:         }
 9445:         if (@sections > 0) {
 9446:             foreach my $item (@sections) {
 9447:                 my ($sec,$gp) = split/:/,$item;
 9448:                 my $class = $args->{'crscode'}.$sec;
 9449:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9450:                 $cenv{'internal.sectionnums'} .= $item.',';
 9451:                 unless ($addcheck eq 'ok') {
 9452:                     push @badclasses, $class;
 9453:                 }
 9454:             }
 9455:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9456:         }
 9457:     }
 9458: # do not hide course coordinator from staff listing, 
 9459: # even if privileged
 9460:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9461: # add crosslistings
 9462:     if ($args->{'crsxlist'}) {
 9463:         $cenv{'internal.crosslistings'}='';
 9464:         if ($args->{'crsxlist'} =~ m/,/) {
 9465:             @xlists = split/,/,$args->{'crsxlist'};
 9466:         } else {
 9467:             $xlists[0] = $args->{'crsxlist'};
 9468:         }
 9469:         if (@xlists > 0) {
 9470:             foreach my $item (@xlists) {
 9471:                 my ($xl,$gp) = split/:/,$item;
 9472:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9473:                 $cenv{'internal.crosslistings'} .= $item.',';
 9474:                 unless ($addcheck eq 'ok') {
 9475:                     push @badclasses, $xl;
 9476:                 }
 9477:             }
 9478:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9479:         }
 9480:     }
 9481:     if ($args->{'autoadds'}) {
 9482:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9483:     }
 9484:     if ($args->{'autodrops'}) {
 9485:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9486:     }
 9487: # check for notification of enrollment changes
 9488:     my @notified = ();
 9489:     if ($args->{'notify_owner'}) {
 9490:         if ($args->{'ccuname'} ne '') {
 9491:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9492:         }
 9493:     }
 9494:     if ($args->{'notify_dc'}) {
 9495:         if ($uname ne '') { 
 9496:             push(@notified,$uname.':'.$udom);
 9497:         }
 9498:     }
 9499:     if (@notified > 0) {
 9500:         my $notifylist;
 9501:         if (@notified > 1) {
 9502:             $notifylist = join(',',@notified);
 9503:         } else {
 9504:             $notifylist = $notified[0];
 9505:         }
 9506:         $cenv{'internal.notifylist'} = $notifylist;
 9507:     }
 9508:     if (@badclasses > 0) {
 9509:         my %lt=&Apache::lonlocal::texthash(
 9510:                 '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',
 9511:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9512:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9513:         );
 9514:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9515:                            ' ('.$lt{'adby'}.')';
 9516:         if ($context eq 'auto') {
 9517:             $outcome .= $badclass_msg.$linefeed;
 9518:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9519:             foreach my $item (@badclasses) {
 9520:                 if ($context eq 'auto') {
 9521:                     $outcome .= " - $item\n";
 9522:                 } else {
 9523:                     $outcome .= "<li>$item</li>\n";
 9524:                 }
 9525:             }
 9526:             if ($context eq 'auto') {
 9527:                 $outcome .= $linefeed;
 9528:             } else {
 9529:                 $outcome .= "</ul><br /><br /></div>\n";
 9530:             }
 9531:         } 
 9532:     }
 9533:     if ($args->{'no_end_date'}) {
 9534:         $args->{'endaccess'} = 0;
 9535:     }
 9536:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9537:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9538:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9539:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9540:     if ($args->{'showphotos'}) {
 9541:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9542:     }
 9543:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9544:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9545:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9546:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9547:             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'); 
 9548:             if ($context eq 'auto') {
 9549:                 $outcome .= $krb_msg;
 9550:             } else {
 9551:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9552:             }
 9553:             $outcome .= $linefeed;
 9554:         }
 9555:     }
 9556:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9557:        if ($args->{'setpolicy'}) {
 9558:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9559:        }
 9560:        if ($args->{'setcontent'}) {
 9561:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9562:        }
 9563:     }
 9564:     if ($args->{'reshome'}) {
 9565: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9566: 	$cenv{'reshome'}=~s/\/+$/\//;
 9567:     }
 9568: #
 9569: # course has keyed access
 9570: #
 9571:     if ($args->{'setkeys'}) {
 9572:        $cenv{'keyaccess'}='yes';
 9573:     }
 9574: # if specified, key authority is not course, but user
 9575: # only active if keyaccess is yes
 9576:     if ($args->{'keyauth'}) {
 9577: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9578: 	$user = &LONCAPA::clean_username($user);
 9579: 	$domain = &LONCAPA::clean_username($domain);
 9580: 	if ($user ne '' && $domain ne '') {
 9581: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9582: 	}
 9583:     }
 9584: 
 9585:     if ($args->{'disresdis'}) {
 9586:         $cenv{'pch.roles.denied'}='st';
 9587:     }
 9588:     if ($args->{'disablechat'}) {
 9589:         $cenv{'plc.roles.denied'}='st';
 9590:     }
 9591: 
 9592:     # Record we've not yet viewed the Course Initialization Helper for this 
 9593:     # course
 9594:     $cenv{'course.helper.not.run'} = 1;
 9595:     #
 9596:     # Use new Randomseed
 9597:     #
 9598:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9599:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9600:     #
 9601:     # The encryption code and receipt prefix for this course
 9602:     #
 9603:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9604:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9605:     #
 9606:     # By default, use standard grading
 9607:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9608: 
 9609:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9610:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9611: #
 9612: # Open all assignments
 9613: #
 9614:     if ($args->{'openall'}) {
 9615:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9616:        my %storecontent = ($storeunder         => time,
 9617:                            $storeunder.'.type' => 'date_start');
 9618:        
 9619:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9620:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9621:    }
 9622: #
 9623: # Set first page
 9624: #
 9625:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9626: 	    || ($cloneid)) {
 9627: 	use LONCAPA::map;
 9628: 	$outcome .= &mt('Setting first resource').': ';
 9629: 
 9630: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9631:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9632: 
 9633:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9634:         my $title; my $url;
 9635:         if ($args->{'firstres'} eq 'syl') {
 9636: 	    $title=&mt('Syllabus');
 9637:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9638:         } else {
 9639:             $title=&mt('Navigate Contents');
 9640:             $url='/adm/navmaps';
 9641:         }
 9642: 
 9643:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9644: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9645: 
 9646: 	if ($errtext) { $fatal=2; }
 9647:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9648:     }
 9649: 
 9650:     return (1,$outcome);
 9651: }
 9652: 
 9653: ############################################################
 9654: ############################################################
 9655: 
 9656: sub course_type {
 9657:     my ($cid) = @_;
 9658:     if (!defined($cid)) {
 9659:         $cid = $env{'request.course.id'};
 9660:     }
 9661:     if (defined($env{'course.'.$cid.'.type'})) {
 9662:         return $env{'course.'.$cid.'.type'};
 9663:     } else {
 9664:         return 'Course';
 9665:     }
 9666: }
 9667: 
 9668: sub group_term {
 9669:     my $crstype = &course_type();
 9670:     my %names = (
 9671:                   'Course' => 'group',
 9672:                   'Group' => 'team',
 9673:                 );
 9674:     return $names{$crstype};
 9675: }
 9676: 
 9677: sub icon {
 9678:     my ($file)=@_;
 9679:     my $curfext = lc((split(/\./,$file))[-1]);
 9680:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9681:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9682:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9683: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9684: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9685: 	            $curfext.".gif") {
 9686: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9687: 		$curfext.".gif";
 9688: 	}
 9689:     }
 9690:     return &lonhttpdurl($iconname);
 9691: } 
 9692: 
 9693: sub lonhttpdurl {
 9694: #
 9695: # Had been used for "small fry" static images on separate port 8080.
 9696: # Modify here if lightweight http functionality desired again.
 9697: # Currently eliminated due to increasing firewall issues.
 9698: #
 9699:     my ($url)=@_;
 9700:     return $url;
 9701: }
 9702: 
 9703: sub connection_aborted {
 9704:     my ($r)=@_;
 9705:     $r->print(" ");$r->rflush();
 9706:     my $c = $r->connection;
 9707:     return $c->aborted();
 9708: }
 9709: 
 9710: #    Escapes strings that may have embedded 's that will be put into
 9711: #    strings as 'strings'.
 9712: sub escape_single {
 9713:     my ($input) = @_;
 9714:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9715:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9716:     return $input;
 9717: }
 9718: 
 9719: #  Same as escape_single, but escape's "'s  This 
 9720: #  can be used for  "strings"
 9721: sub escape_double {
 9722:     my ($input) = @_;
 9723:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9724:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9725:     return $input;
 9726: }
 9727:  
 9728: #   Escapes the last element of a full URL.
 9729: sub escape_url {
 9730:     my ($url)   = @_;
 9731:     my @urlslices = split(/\//, $url,-1);
 9732:     my $lastitem = &escape(pop(@urlslices));
 9733:     return join('/',@urlslices).'/'.$lastitem;
 9734: }
 9735: 
 9736: # -------------------------------------------------------- Initliaze user login
 9737: sub init_user_environment {
 9738:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9739:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9740: 
 9741:     my $public=($username eq 'public' && $domain eq 'public');
 9742: 
 9743: # See if old ID present, if so, remove
 9744: 
 9745:     my ($filename,$cookie,$userroles);
 9746:     my $now=time;
 9747: 
 9748:     if ($public) {
 9749: 	my $max_public=100;
 9750: 	my $oldest;
 9751: 	my $oldest_time=0;
 9752: 	for(my $next=1;$next<=$max_public;$next++) {
 9753: 	    if (-e $lonids."/publicuser_$next.id") {
 9754: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9755: 		if ($mtime<$oldest_time || !$oldest_time) {
 9756: 		    $oldest_time=$mtime;
 9757: 		    $oldest=$next;
 9758: 		}
 9759: 	    } else {
 9760: 		$cookie="publicuser_$next";
 9761: 		last;
 9762: 	    }
 9763: 	}
 9764: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9765:     } else {
 9766: 	# if this isn't a robot, kill any existing non-robot sessions
 9767: 	if (!$args->{'robot'}) {
 9768: 	    opendir(DIR,$lonids);
 9769: 	    while ($filename=readdir(DIR)) {
 9770: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9771: 		    unlink($lonids.'/'.$filename);
 9772: 		}
 9773: 	    }
 9774: 	    closedir(DIR);
 9775: 	}
 9776: # Give them a new cookie
 9777: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9778: 		                   : $now.$$.int(rand(10000)));
 9779: 	$cookie="$username\_$id\_$domain\_$authhost";
 9780:     
 9781: # Initialize roles
 9782: 
 9783: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9784:     }
 9785: # ------------------------------------ Check browser type and MathML capability
 9786: 
 9787:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9788:         $clientunicode,$clientos) = &decode_user_agent($r);
 9789: 
 9790: # -------------------------------------- Any accessibility options to remember?
 9791:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9792: 	foreach my $option ('imagesuppress','appletsuppress',
 9793: 			    'embedsuppress','fontenhance','blackwhite') {
 9794: 	    if ($form->{$option} eq 'true') {
 9795: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9796: 				     $domain,$username);
 9797: 	    } else {
 9798: 		&Apache::lonnet::del('environment',[$option],
 9799: 				     $domain,$username);
 9800: 	    }
 9801: 	}
 9802:     }
 9803: # ------------------------------------------------------------- Get environment
 9804: 
 9805:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9806:     my ($tmp) = keys(%userenv);
 9807:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9808: 	# default remote control to off
 9809: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9810:     } else {
 9811: 	undef(%userenv);
 9812:     }
 9813:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9814: 	$form->{'interface'}=$userenv{'interface'};
 9815:     }
 9816:     $env{'environment.remote'}=$userenv{'remote'};
 9817:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9818: 
 9819: # --------------- Do not trust query string to be put directly into environment
 9820:     foreach my $option ('imagesuppress','appletsuppress',
 9821: 			'embedsuppress','fontenhance','blackwhite',
 9822: 			'interface','localpath','localres') {
 9823: 	$form->{$option}=~s/[\n\r\=]//gs;
 9824:     }
 9825: # --------------------------------------------------------- Write first profile
 9826: 
 9827:     {
 9828: 	my %initial_env = 
 9829: 	    ("user.name"          => $username,
 9830: 	     "user.domain"        => $domain,
 9831: 	     "user.home"          => $authhost,
 9832: 	     "browser.type"       => $clientbrowser,
 9833: 	     "browser.version"    => $clientversion,
 9834: 	     "browser.mathml"     => $clientmathml,
 9835: 	     "browser.unicode"    => $clientunicode,
 9836: 	     "browser.os"         => $clientos,
 9837: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9838: 	     "request.course.fn"  => '',
 9839: 	     "request.course.uri" => '',
 9840: 	     "request.course.sec" => '',
 9841: 	     "request.role"       => 'cm',
 9842: 	     "request.role.adv"   => $env{'user.adv'},
 9843: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9844: 
 9845:         if ($form->{'localpath'}) {
 9846: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9847: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9848:         }
 9849: 	
 9850: 	if ($public) {
 9851: 	    $initial_env{"environment.remote"} = "off";
 9852: 	}
 9853: 	if ($form->{'interface'}) {
 9854: 	    $form->{'interface'}=~s/\W//gs;
 9855: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9856: 	    $env{'browser.interface'}=$form->{'interface'};
 9857: 	    foreach my $option ('imagesuppress','appletsuppress',
 9858: 				'embedsuppress','fontenhance','blackwhite') {
 9859: 		if (($form->{$option} eq 'true') ||
 9860: 		    ($userenv{$option} eq 'on')) {
 9861: 		    $initial_env{"browser.$option"} = "on";
 9862: 		}
 9863: 	    }
 9864: 	}
 9865: 
 9866:         foreach my $tool ('aboutme','blog','portfolio') {
 9867:             $userenv{'availabletools.'.$tool} = 
 9868:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9869:         }
 9870: 
 9871: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9872: 	
 9873: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9874: 		 &GDBM_WRCREAT(),0640)) {
 9875: 	    &_add_to_env(\%disk_env,\%initial_env);
 9876: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9877: 	    &_add_to_env(\%disk_env,$userroles);
 9878: 	    if (ref($args->{'extra_env'})) {
 9879: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9880: 	    }
 9881: 	    untie(%disk_env);
 9882: 	} else {
 9883: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
 9884: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
 9885: 	    return 'error: '.$!;
 9886: 	}
 9887:     }
 9888:     $env{'request.role'}='cm';
 9889:     $env{'request.role.adv'}=$env{'user.adv'};
 9890:     $env{'browser.type'}=$clientbrowser;
 9891: 
 9892:     return $cookie;
 9893: 
 9894: }
 9895: 
 9896: sub _add_to_env {
 9897:     my ($idf,$env_data,$prefix) = @_;
 9898:     if (ref($env_data) eq 'HASH') {
 9899:         while (my ($key,$value) = each(%$env_data)) {
 9900: 	    $idf->{$prefix.$key} = $value;
 9901: 	    $env{$prefix.$key}   = $value;
 9902:         }
 9903:     }
 9904: }
 9905: 
 9906: # --- Get the symbolic name of a problem and the url
 9907: sub get_symb {
 9908:     my ($request,$silent) = @_;
 9909:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9910:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
 9911:     if ($symb eq '') {
 9912:         if (!$silent) {
 9913:             $request->print("Unable to handle ambiguous references:$url:.");
 9914:             return ();
 9915:         }
 9916:     }
 9917:     &Apache::lonenc::check_decrypt(\$symb);
 9918:     return ($symb);
 9919: }
 9920: 
 9921: # --------------------------------------------------------------Get annotation
 9922: 
 9923: sub get_annotation {
 9924:     my ($symb,$enc) = @_;
 9925: 
 9926:     my $key = $symb;
 9927:     if (!$enc) {
 9928:         $key =
 9929:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 9930:     }
 9931:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
 9932:     return $annotation{$key};
 9933: }
 9934: 
 9935: sub clean_symb {
 9936:     my ($symb,$delete_enc) = @_;
 9937: 
 9938:     &Apache::lonenc::check_decrypt(\$symb);
 9939:     my $enc = $env{'request.enc'};
 9940:     if ($delete_enc) {
 9941:         delete($env{'request.enc'});
 9942:     }
 9943: 
 9944:     return ($symb,$enc);
 9945: }
 9946: 
 9947: =pod
 9948: 
 9949: =back
 9950: 
 9951: =cut
 9952: 
 9953: 1;
 9954: __END__;
 9955: 

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