File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.648: download - view: text, annotated - select for diffs
Sun Mar 23 21:40:10 2008 UTC (16 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Changes to pod so output looks more consistent after running pod2html over it.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.648 2008/03/23 21:40:10 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use HTML::Entities;
   65: use Apache::lonhtmlcommon();
   66: use Apache::loncoursedata();
   67: use Apache::lontexconvert();
   68: use Apache::lonclonecourse();
   69: use LONCAPA qw(:DEFAULT :match);
   70: 
   71: # ---------------------------------------------- Designs
   72: use vars qw(%defaultdesign);
   73: 
   74: my $readit;
   75: 
   76: 
   77: ##
   78: ## Global Variables
   79: ##
   80: 
   81: 
   82: # ----------------------------------------------- SSI with retries:
   83: #
   84: 
   85: =pod
   86: 
   87: =head1 Server Side include with retries:
   88: 
   89: =over 4
   90: 
   91: =item * &ssi_with_retries(resource,retries form)
   92: 
   93: Performs an ssi with some number of retries.  Retries continue either
   94: until the result is ok or until the retry count supplied by the
   95: caller is exhausted.  
   96: 
   97: Inputs:
   98: 
   99: =over 4
  100: 
  101: resource   - Identifies the resource to insert.
  102: 
  103: retries    - Count of the number of retries allowed.
  104: 
  105: form       - Hash that identifies the rendering options.
  106: 
  107: =back
  108: 
  109: Returns:
  110: 
  111: =over 4
  112: 
  113: content    - The content of the response.  If retries were exhausted this is empty.
  114: 
  115: response   - The response from the last attempt (which may or may not have been successful.
  116: 
  117: =back
  118: 
  119: =back
  120: 
  121: =cut
  122: 
  123: sub ssi_with_retries {
  124:     my ($resource, $retries, %form) = @_;
  125: 
  126: 
  127:     my $ok = 0;			# True if we got a good response.
  128:     my $content;
  129:     my $response;
  130: 
  131:     # Try to get the ssi done. within the retries count:
  132: 
  133:     do {
  134: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  135: 	$ok      = $response->is_success;
  136: 	$retries--;
  137:     } while (!$ok && ($retries > 0));
  138: 
  139:     if (!$ok) {
  140: 	$content = '';		# On error return an empty content.
  141:     }
  142:     return ($content, $response);
  143: 
  144: }
  145: 
  146: 
  147: 
  148: # ----------------------------------------------- Filetypes/Languages/Copyright
  149: my %language;
  150: my %supported_language;
  151: my %cprtag;
  152: my %scprtag;
  153: my %fe; my %fd; my %fm;
  154: my %category_extensions;
  155: 
  156: # ---------------------------------------------- Thesaurus variables
  157: #
  158: # %Keywords:
  159: #      A hash used by &keyword to determine if a word is considered a keyword.
  160: # $thesaurus_db_file 
  161: #      Scalar containing the full path to the thesaurus database.
  162: 
  163: my %Keywords;
  164: my $thesaurus_db_file;
  165: 
  166: #
  167: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  168: # thesaurus.tab, and filecategories.tab.
  169: #
  170: BEGIN {
  171:     # Variable initialization
  172:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  173:     #
  174:     unless ($readit) {
  175: # ------------------------------------------------------------------- languages
  176:     {
  177:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  178:                                    '/language.tab';
  179:         if ( open(my $fh,"<$langtabfile") ) {
  180:             while (my $line = <$fh>) {
  181:                 next if ($line=~/^\#/);
  182:                 chomp($line);
  183:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  184:                 $language{$key}=$val.' - '.$enc;
  185:                 if ($sup) {
  186:                     $supported_language{$key}=$sup;
  187:                 }
  188:             }
  189:             close($fh);
  190:         }
  191:     }
  192: # ------------------------------------------------------------------ copyrights
  193:     {
  194:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  195:                                   '/copyright.tab';
  196:         if ( open (my $fh,"<$copyrightfile") ) {
  197:             while (my $line = <$fh>) {
  198:                 next if ($line=~/^\#/);
  199:                 chomp($line);
  200:                 my ($key,$val)=(split(/\s+/,$line,2));
  201:                 $cprtag{$key}=$val;
  202:             }
  203:             close($fh);
  204:         }
  205:     }
  206: # ----------------------------------------------------------- source copyrights
  207:     {
  208:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  209:                                   '/source_copyright.tab';
  210:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  211:             while (my $line = <$fh>) {
  212:                 next if ($line =~ /^\#/);
  213:                 chomp($line);
  214:                 my ($key,$val)=(split(/\s+/,$line,2));
  215:                 $scprtag{$key}=$val;
  216:             }
  217:             close($fh);
  218:         }
  219:     }
  220: 
  221: # -------------------------------------------------------------- default domain designs
  222:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  223:     my $designfile = $designdir.'/default.tab';
  224:     if ( open (my $fh,"<$designfile") ) {
  225:         while (my $line = <$fh>) {
  226:             next if ($line =~ /^\#/);
  227:             chomp($line);
  228:             my ($key,$val)=(split(/\=/,$line));
  229:             if ($val) { $defaultdesign{$key}=$val; }
  230:         }
  231:         close($fh);
  232:     }
  233: 
  234: # ------------------------------------------------------------- file categories
  235:     {
  236:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  237:                                   '/filecategories.tab';
  238:         if ( open (my $fh,"<$categoryfile") ) {
  239: 	    while (my $line = <$fh>) {
  240: 		next if ($line =~ /^\#/);
  241: 		chomp($line);
  242:                 my ($extension,$category)=(split(/\s+/,$line,2));
  243:                 push @{$category_extensions{lc($category)}},$extension;
  244:             }
  245:             close($fh);
  246:         }
  247: 
  248:     }
  249: # ------------------------------------------------------------------ file types
  250:     {
  251:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  252:                '/filetypes.tab';
  253:         if ( open (my $fh,"<$typesfile") ) {
  254:             while (my $line = <$fh>) {
  255: 		next if ($line =~ /^\#/);
  256: 		chomp($line);
  257:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  258:                 if ($descr ne '') {
  259:                     $fe{$ending}=lc($emb);
  260:                     $fd{$ending}=$descr;
  261:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  262:                 }
  263:             }
  264:             close($fh);
  265:         }
  266:     }
  267:     &Apache::lonnet::logthis(
  268:               "<font color=yellow>INFO: Read file types</font>");
  269:     $readit=1;
  270:     }  # end of unless($readit) 
  271:     
  272: }
  273: 
  274: ###############################################################
  275: ##           HTML and Javascript Helper Functions            ##
  276: ###############################################################
  277: 
  278: =pod 
  279: 
  280: =head1 HTML and Javascript Functions
  281: 
  282: =over 4
  283: 
  284: =item * &browser_and_searcher_javascript()
  285: 
  286: X<browsing, javascript>X<searching, javascript>Returns a string
  287: containing javascript with two functions, C<openbrowser> and
  288: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  289: tags.
  290: 
  291: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  292: 
  293: inputs: formname, elementname, only, omit
  294: 
  295: formname and elementname indicate the name of the html form and name of
  296: the element that the results of the browsing selection are to be placed in. 
  297: 
  298: Specifying 'only' will restrict the browser to displaying only files
  299: with the given extension.  Can be a comma separated list.
  300: 
  301: Specifying 'omit' will restrict the browser to NOT displaying files
  302: with the given extension.  Can be a comma separated list.
  303: 
  304: =item * &opensearcher(formname,elementname) [javascript]
  305: 
  306: Inputs: formname, elementname
  307: 
  308: formname and elementname specify the name of the html form and the name
  309: of the element the selection from the search results will be placed in.
  310: 
  311: =cut
  312: 
  313: sub browser_and_searcher_javascript {
  314:     my ($mode)=@_;
  315:     if (!defined($mode)) { $mode='edit'; }
  316:     my $resurl=&escape_single(&lastresurl());
  317:     return <<END;
  318: // <!-- BEGIN LON-CAPA Internal
  319:     var editbrowser = null;
  320:     function openbrowser(formname,elementname,only,omit,titleelement) {
  321:         var url = '$resurl/?';
  322:         if (editbrowser == null) {
  323:             url += 'launch=1&';
  324:         }
  325:         url += 'catalogmode=interactive&';
  326:         url += 'mode=$mode&';
  327:         url += 'inhibitmenu=yes&';
  328:         url += 'form=' + formname + '&';
  329:         if (only != null) {
  330:             url += 'only=' + only + '&';
  331:         } else {
  332:             url += 'only=&';
  333: 	}
  334:         if (omit != null) {
  335:             url += 'omit=' + omit + '&';
  336:         } else {
  337:             url += 'omit=&';
  338: 	}
  339:         if (titleelement != null) {
  340:             url += 'titleelement=' + titleelement + '&';
  341:         } else {
  342: 	    url += 'titleelement=&';
  343: 	}
  344:         url += 'element=' + elementname + '';
  345:         var title = 'Browser';
  346:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  347:         options += ',width=700,height=600';
  348:         editbrowser = open(url,title,options,'1');
  349:         editbrowser.focus();
  350:     }
  351:     var editsearcher;
  352:     function opensearcher(formname,elementname,titleelement) {
  353:         var url = '/adm/searchcat?';
  354:         if (editsearcher == null) {
  355:             url += 'launch=1&';
  356:         }
  357:         url += 'catalogmode=interactive&';
  358:         url += 'mode=$mode&';
  359:         url += 'form=' + formname + '&';
  360:         if (titleelement != null) {
  361:             url += 'titleelement=' + titleelement + '&';
  362:         } else {
  363: 	    url += 'titleelement=&';
  364: 	}
  365:         url += 'element=' + elementname + '';
  366:         var title = 'Search';
  367:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  368:         options += ',width=700,height=600';
  369:         editsearcher = open(url,title,options,'1');
  370:         editsearcher.focus();
  371:     }
  372: // END LON-CAPA Internal -->
  373: END
  374: }
  375: 
  376: sub lastresurl {
  377:     if ($env{'environment.lastresurl'}) {
  378: 	return $env{'environment.lastresurl'}
  379:     } else {
  380: 	return '/res';
  381:     }
  382: }
  383: 
  384: sub storeresurl {
  385:     my $resurl=&Apache::lonnet::clutter(shift);
  386:     unless ($resurl=~/^\/res/) { return 0; }
  387:     $resurl=~s/\/$//;
  388:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  389:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  390:     return 1;
  391: }
  392: 
  393: sub studentbrowser_javascript {
  394:    unless (
  395:             (($env{'request.course.id'}) && 
  396:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  397: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  398: 					  '/'.$env{'request.course.sec'})
  399: 	      ))
  400:          || ($env{'request.role'}=~/^(au|dc|su)/)
  401:           ) { return ''; }  
  402:    return (<<'ENDSTDBRW');
  403: <script type="text/javascript" language="Javascript" >
  404:     var stdeditbrowser;
  405:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  406:         var url = '/adm/pickstudent?';
  407:         var filter;
  408: 	if (!ignorefilter) {
  409: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  410: 	}
  411:         if (filter != null) {
  412:            if (filter != '') {
  413:                url += 'filter='+filter+'&';
  414: 	   }
  415:         }
  416:         url += 'form=' + formname + '&unameelement='+uname+
  417:                                     '&udomelement='+udom;
  418: 	if (roleflag) { url+="&roles=1"; }
  419:         var title = 'Student_Browser';
  420:         var options = 'scrollbars=1,resizable=1,menubar=0';
  421:         options += ',width=700,height=600';
  422:         stdeditbrowser = open(url,title,options,'1');
  423:         stdeditbrowser.focus();
  424:     }
  425: </script>
  426: ENDSTDBRW
  427: }
  428: 
  429: sub selectstudent_link {
  430:    my ($form,$unameele,$udomele)=@_;
  431:    if ($env{'request.course.id'}) {  
  432:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  433: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  434: 					'/'.$env{'request.course.sec'})) {
  435: 	   return '';
  436:        }
  437:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  438:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  439:    }
  440:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  441:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  442:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  443:    }
  444:    return '';
  445: }
  446: 
  447: sub coursebrowser_javascript {
  448:     my ($domainfilter,$sec_element,$formname)=@_;
  449:     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');
  450:    my $output = '
  451: <script type="text/javascript">
  452:     var stdeditbrowser;'."\n";
  453:    $output .= <<"ENDSTDBRW";
  454:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  455:         var url = '/adm/pickcourse?';
  456:         var domainfilter = '';
  457:         var formid = getFormIdByName(formname);
  458:         if (formid > -1) {
  459:             var domid = getIndexByName(formid,udom);
  460:             if (domid > -1) {
  461:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  462:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  463:                 }
  464:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  465:                     domainfilter=document.forms[formid].elements[domid].value;
  466:                 }
  467:             }
  468:         }
  469:         if (domainfilter != null) {
  470:            if (domainfilter != '') {
  471:                url += 'domainfilter='+domainfilter+'&';
  472: 	   }
  473:         }
  474:         url += 'form=' + formname + '&cnumelement='+uname+
  475: 	                            '&cdomelement='+udom+
  476:                                     '&cnameelement='+desc;
  477:         if (extra_element !=null && extra_element != '') {
  478:             if (formname == 'rolechoice' || formname == 'studentform') {
  479:                 url += '&roleelement='+extra_element;
  480:                 if (domainfilter == null || domainfilter == '') {
  481:                     url += '&domainfilter='+extra_element;
  482:                 }
  483:             }
  484:             else {
  485:                 if (formname == 'portform') {
  486:                     url += '&setroles='+extra_element;
  487:                 }
  488:             }     
  489:         }
  490:         if (multflag !=null && multflag != '') {
  491:             url += '&multiple='+multflag;
  492:         }
  493:         if (crstype == 'Course/Group') {
  494:             if (formname == 'cu') {
  495:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  496:                 if (crstype == "") {
  497:                     alert("$crs_or_grp_alert");
  498:                     return;
  499:                 }
  500:             }
  501:         }
  502:         if (crstype !=null && crstype != '') {
  503:             url += '&type='+crstype;
  504:         }
  505:         var title = 'Course_Browser';
  506:         var options = 'scrollbars=1,resizable=1,menubar=0';
  507:         options += ',width=700,height=600';
  508:         stdeditbrowser = open(url,title,options,'1');
  509:         stdeditbrowser.focus();
  510:     }
  511: 
  512:     function getFormIdByName(formname) {
  513:         for (var i=0;i<document.forms.length;i++) {
  514:             if (document.forms[i].name == formname) {
  515:                 return i;
  516:             }
  517:         }
  518:         return -1; 
  519:     }
  520: 
  521:     function getIndexByName(formid,item) {
  522:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  523:             if (document.forms[formid].elements[i].name == item) {
  524:                 return i;
  525:             }
  526:         }
  527:         return -1;
  528:     }
  529: ENDSTDBRW
  530:     if ($sec_element ne '') {
  531:         $output .= &setsec_javascript($sec_element,$formname);
  532:     }
  533:     $output .= '
  534: </script>';
  535:     return $output;
  536: }
  537: 
  538: sub setsec_javascript {
  539:     my ($sec_element,$formname) = @_;
  540:     my $setsections = qq|
  541: function setSect(sectionlist) {
  542:     var sectionsArray = new Array();
  543:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  544:         sectionsArray = sectionlist.split(",");
  545:     }
  546:     var numSections = sectionsArray.length;
  547:     document.$formname.$sec_element.length = 0;
  548:     if (numSections == 0) {
  549:         document.$formname.$sec_element.multiple=false;
  550:         document.$formname.$sec_element.size=1;
  551:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  552:     } else {
  553:         if (numSections == 1) {
  554:             document.$formname.$sec_element.multiple=false;
  555:             document.$formname.$sec_element.size=1;
  556:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  557:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  558:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  559:         } else {
  560:             for (var i=0; i<numSections; i++) {
  561:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  562:             }
  563:             document.$formname.$sec_element.multiple=true
  564:             if (numSections < 3) {
  565:                 document.$formname.$sec_element.size=numSections;
  566:             } else {
  567:                 document.$formname.$sec_element.size=3;
  568:             }
  569:             document.$formname.$sec_element.options[0].selected = false
  570:         }
  571:     }
  572: }
  573: |;
  574:     return $setsections;
  575: }
  576: 
  577: 
  578: sub selectcourse_link {
  579:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  580:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  581:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  582: }
  583: 
  584: sub check_uncheck_jscript {
  585:     my $jscript = <<"ENDSCRT";
  586: function checkAll(field) {
  587:     if (field.length > 0) {
  588:         for (i = 0; i < field.length; i++) {
  589:             field[i].checked = true ;
  590:         }
  591:     } else {
  592:         field.checked = true
  593:     }
  594: }
  595:  
  596: function uncheckAll(field) {
  597:     if (field.length > 0) {
  598:         for (i = 0; i < field.length; i++) {
  599:             field[i].checked = false ;
  600:         }
  601:     } else {
  602:         field.checked = false ;
  603:     }
  604: }
  605: ENDSCRT
  606:     return $jscript;
  607: }
  608: 
  609: 
  610: =pod
  611: 
  612: =item * &linked_select_forms(...)
  613: 
  614: linked_select_forms returns a string containing a <script></script> block
  615: and html for two <select> menus.  The select menus will be linked in that
  616: changing the value of the first menu will result in new values being placed
  617: in the second menu.  The values in the select menu will appear in alphabetical
  618: order unless a defined order is provided.
  619: 
  620: linked_select_forms takes the following ordered inputs:
  621: 
  622: =over 4
  623: 
  624: =item * $formname, the name of the <form> tag
  625: 
  626: =item * $middletext, the text which appears between the <select> tags
  627: 
  628: =item * $firstdefault, the default value for the first menu
  629: 
  630: =item * $firstselectname, the name of the first <select> tag
  631: 
  632: =item * $secondselectname, the name of the second <select> tag
  633: 
  634: =item * $hashref, a reference to a hash containing the data for the menus.
  635: 
  636: =item * $menuorder, the order of values in the first menu
  637: 
  638: =back 
  639: 
  640: Below is an example of such a hash.  Only the 'text', 'default', and 
  641: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  642: values for the first select menu.  The text that coincides with the 
  643: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  644: and text for the second menu are given in the hash pointed to by 
  645: $menu{$choice1}->{'select2'}.  
  646: 
  647:  my %menu = ( A1 => { text =>"Choice A1" ,
  648:                        default => "B3",
  649:                        select2 => { 
  650:                            B1 => "Choice B1",
  651:                            B2 => "Choice B2",
  652:                            B3 => "Choice B3",
  653:                            B4 => "Choice B4"
  654:                            },
  655:                        order => ['B4','B3','B1','B2'],
  656:                    },
  657:                A2 => { text =>"Choice A2" ,
  658:                        default => "C2",
  659:                        select2 => { 
  660:                            C1 => "Choice C1",
  661:                            C2 => "Choice C2",
  662:                            C3 => "Choice C3"
  663:                            },
  664:                        order => ['C2','C1','C3'],
  665:                    },
  666:                A3 => { text =>"Choice A3" ,
  667:                        default => "D6",
  668:                        select2 => { 
  669:                            D1 => "Choice D1",
  670:                            D2 => "Choice D2",
  671:                            D3 => "Choice D3",
  672:                            D4 => "Choice D4",
  673:                            D5 => "Choice D5",
  674:                            D6 => "Choice D6",
  675:                            D7 => "Choice D7"
  676:                            },
  677:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  678:                    }
  679:                );
  680: 
  681: =cut
  682: 
  683: sub linked_select_forms {
  684:     my ($formname,
  685:         $middletext,
  686:         $firstdefault,
  687:         $firstselectname,
  688:         $secondselectname, 
  689:         $hashref,
  690:         $menuorder,
  691:         ) = @_;
  692:     my $second = "document.$formname.$secondselectname";
  693:     my $first = "document.$formname.$firstselectname";
  694:     # output the javascript to do the changing
  695:     my $result = '';
  696:     $result.="<script type=\"text/javascript\">\n";
  697:     $result.="var select2data = new Object();\n";
  698:     $" = '","';
  699:     my $debug = '';
  700:     foreach my $s1 (sort(keys(%$hashref))) {
  701:         $result.="select2data.d_$s1 = new Object();\n";        
  702:         $result.="select2data.d_$s1.def = new String('".
  703:             $hashref->{$s1}->{'default'}."');\n";
  704:         $result.="select2data.d_$s1.values = new Array(";
  705:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  706:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  707:             @s2values = @{$hashref->{$s1}->{'order'}};
  708:         }
  709:         $result.="\"@s2values\");\n";
  710:         $result.="select2data.d_$s1.texts = new Array(";        
  711:         my @s2texts;
  712:         foreach my $value (@s2values) {
  713:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  714:         }
  715:         $result.="\"@s2texts\");\n";
  716:     }
  717:     $"=' ';
  718:     $result.= <<"END";
  719: 
  720: function select1_changed() {
  721:     // Determine new choice
  722:     var newvalue = "d_" + $first.value;
  723:     // update select2
  724:     var values     = select2data[newvalue].values;
  725:     var texts      = select2data[newvalue].texts;
  726:     var select2def = select2data[newvalue].def;
  727:     var i;
  728:     // out with the old
  729:     for (i = 0; i < $second.options.length; i++) {
  730:         $second.options[i] = null;
  731:     }
  732:     // in with the nuclear
  733:     for (i=0;i<values.length; i++) {
  734:         $second.options[i] = new Option(values[i]);
  735:         $second.options[i].value = values[i];
  736:         $second.options[i].text = texts[i];
  737:         if (values[i] == select2def) {
  738:             $second.options[i].selected = true;
  739:         }
  740:     }
  741: }
  742: </script>
  743: END
  744:     # output the initial values for the selection lists
  745:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  746:     my @order = sort(keys(%{$hashref}));
  747:     if (ref($menuorder) eq 'ARRAY') {
  748:         @order = @{$menuorder};
  749:     }
  750:     foreach my $value (@order) {
  751:         $result.="    <option value=\"$value\" ";
  752:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  753:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  754:     }
  755:     $result .= "</select>\n";
  756:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  757:     $result .= $middletext;
  758:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  759:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  760:     
  761:     my @secondorder = sort(keys(%select2));
  762:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  763:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  764:     }
  765:     foreach my $value (@secondorder) {
  766:         $result.="    <option value=\"$value\" ";        
  767:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  768:         $result.=">".&mt($select2{$value})."</option>\n";
  769:     }
  770:     $result .= "</select>\n";
  771:     #    return $debug;
  772:     return $result;
  773: }   #  end of sub linked_select_forms {
  774: 
  775: =pod
  776: 
  777: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  778: 
  779: Returns a string corresponding to an HTML link to the given help
  780: $topic, where $topic corresponds to the name of a .tex file in
  781: /home/httpd/html/adm/help/tex, with underscores replaced by
  782: spaces. 
  783: 
  784: $text will optionally be linked to the same topic, allowing you to
  785: link text in addition to the graphic. If you do not want to link
  786: text, but wish to specify one of the later parameters, pass an
  787: empty string. 
  788: 
  789: $stayOnPage is a value that will be interpreted as a boolean. If true,
  790: the link will not open a new window. If false, the link will open
  791: a new window using Javascript. (Default is false.) 
  792: 
  793: $width and $height are optional numerical parameters that will
  794: override the width and height of the popped up window, which may
  795: be useful for certain help topics with big pictures included. 
  796: 
  797: =cut
  798: 
  799: sub help_open_topic {
  800:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  801:     $text = "" if (not defined $text);
  802:     $stayOnPage = 0 if (not defined $stayOnPage);
  803:     if ($env{'browser.interface'} eq 'textual') {
  804: 	$stayOnPage=1;
  805:     }
  806:     $width = 350 if (not defined $width);
  807:     $height = 400 if (not defined $height);
  808:     my $filename = $topic;
  809:     $filename =~ s/ /_/g;
  810: 
  811:     my $template = "";
  812:     my $link;
  813:     
  814:     $topic=~s/\W/\_/g;
  815: 
  816:     if (!$stayOnPage) {
  817: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  818:     } else {
  819: 	$link = "/adm/help/${filename}.hlp";
  820:     }
  821: 
  822:     # Add the text
  823:     if ($text ne "") {
  824: 	$template .= 
  825:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  826:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  827:     }
  828: 
  829:     # Add the graphic
  830:     my $title = &mt('Online Help');
  831:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
  832:     $template .= <<"ENDTEMPLATE";
  833:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  834: ENDTEMPLATE
  835:     if ($text ne '') { $template.='</td></tr></table>' };
  836:     return $template;
  837: 
  838: }
  839: 
  840: # This is a quicky function for Latex cheatsheet editing, since it 
  841: # appears in at least four places
  842: sub helpLatexCheatsheet {
  843:     my $other = shift;
  844:     my $addOther = '';
  845:     if ($other) {
  846: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  847: 						       undef, undef, 600) .
  848: 							   '</td><td>';
  849:     }
  850:     return '<table><tr><td>'.
  851: 	$addOther .
  852: 	&Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  853: 					    undef,undef,600)
  854: 	.'</td><td>'.
  855: 	&Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
  856: 					    undef,undef,600)
  857: 	.'</td></tr></table>';
  858: }
  859: 
  860: sub general_help {
  861:     my $helptopic='Student_Intro';
  862:     if ($env{'request.role'}=~/^(ca|au)/) {
  863: 	$helptopic='Authoring_Intro';
  864:     } elsif ($env{'request.role'}=~/^cc/) {
  865: 	$helptopic='Course_Coordination_Intro';
  866:     }
  867:     return $helptopic;
  868: }
  869: 
  870: sub update_help_link {
  871:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  872:     my $origurl = $ENV{'REQUEST_URI'};
  873:     $origurl=~s|^/~|/priv/|;
  874:     my $timestamp = time;
  875:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  876:         $$datum = &escape($$datum);
  877:     }
  878: 
  879:     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";
  880:     my $output .= <<"ENDOUTPUT";
  881: <script type="text/javascript">
  882: banner_link = '$banner_link';
  883: </script>
  884: ENDOUTPUT
  885:     return $output;
  886: }
  887: 
  888: # now just updates the help link and generates a blue icon
  889: sub help_open_menu {
  890:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
  891: 	= @_;    
  892:     $stayOnPage = 0 if (not defined $stayOnPage);
  893:     # only use pop-up help (stayOnPage == 0)
  894:     # if environment.remote is on (using remote control UI)
  895:     if ($env{'browser.interface'} eq 'textual' ||
  896:     	$env{'environment.remote'} eq 'off' ) {
  897:         $stayOnPage=1;
  898:     }
  899:     my $output;
  900:     if ($component_help) {
  901: 	if (!$text) {
  902: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
  903: 				       $width,$height);
  904: 	} else {
  905: 	    my $help_text;
  906: 	    $help_text=&unescape($topic);
  907: 	    $output='<table><tr><td>'.
  908: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  909: 				 $width,$height).'</td></tr></table>';
  910: 	}
  911:     }
  912:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
  913:     return $output.$banner_link;
  914: }
  915: 
  916: sub top_nav_help {
  917:     my ($text) = @_;
  918:     $text = &mt($text);
  919:     my $stay_on_page = 
  920: 	($env{'browser.interface'}  eq 'textual' ||
  921: 	 $env{'environment.remote'} eq 'off' );
  922:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
  923: 	                     : "javascript:helpMenu('open')";
  924:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
  925: 
  926:     my $title = &mt('Get help');
  927: 
  928:     return <<"END";
  929: $banner_link
  930:  <a href="$link" title="$title">$text</a>
  931: END
  932: }
  933: 
  934: sub help_menu_js {
  935:     my ($text) = @_;
  936: 
  937:     my $stayOnPage = 
  938: 	($env{'browser.interface'}  eq 'textual' ||
  939: 	 $env{'environment.remote'} eq 'off' );
  940: 
  941:     my $width = 620;
  942:     my $height = 600;
  943:     my $helptopic=&general_help();
  944:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
  945:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  946:     my $start_page =
  947:         &Apache::loncommon::start_page('Help Menu', undef,
  948: 				       {'frameset'    => 1,
  949: 					'js_ready'    => 1,
  950: 					'add_entries' => {
  951: 					    'border' => '0',
  952: 					    'rows'   => "110,*",},});
  953:     my $end_page =
  954:         &Apache::loncommon::end_page({'frameset' => 1,
  955: 				      'js_ready' => 1,});
  956: 
  957:     my $template .= <<"ENDTEMPLATE";
  958: <script type="text/javascript">
  959: // <!-- BEGIN LON-CAPA Internal
  960: // <![CDATA[
  961: var banner_link = '';
  962: function helpMenu(target) {
  963:     var caller = this;
  964:     if (target == 'open') {
  965:         var newWindow = null;
  966:         try {
  967:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
  968:         }
  969:         catch(error) {
  970:             writeHelp(caller);
  971:             return;
  972:         }
  973:         if (newWindow) {
  974:             caller = newWindow;
  975:         }
  976:     }
  977:     writeHelp(caller);
  978:     return;
  979: }
  980: function writeHelp(caller) {
  981:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
  982:     caller.document.close()
  983:     caller.focus()
  984: }
  985: // ]]>
  986: // END LON-CAPA Internal -->
  987: </script>
  988: ENDTEMPLATE
  989:     return $template;
  990: }
  991: 
  992: sub help_open_bug {
  993:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  994:     unless ($env{'user.adv'}) { return ''; }
  995:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  996:     $text = "" if (not defined $text);
  997:     $stayOnPage = 0 if (not defined $stayOnPage);
  998:     if ($env{'browser.interface'} eq 'textual' ||
  999: 	$env{'environment.remote'} eq 'off' ) {
 1000: 	$stayOnPage=1;
 1001:     }
 1002:     $width = 600 if (not defined $width);
 1003:     $height = 600 if (not defined $height);
 1004: 
 1005:     $topic=~s/\W+/\+/g;
 1006:     my $link='';
 1007:     my $template='';
 1008:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1009: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1010:     if (!$stayOnPage)
 1011:     {
 1012: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1013:     }
 1014:     else
 1015:     {
 1016: 	$link = $url;
 1017:     }
 1018:     # Add the text
 1019:     if ($text ne "")
 1020:     {
 1021: 	$template .= 
 1022:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1023:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1024:     }
 1025: 
 1026:     # Add the graphic
 1027:     my $title = &mt('Report a Bug');
 1028:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1029:     $template .= <<"ENDTEMPLATE";
 1030:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1031: ENDTEMPLATE
 1032:     if ($text ne '') { $template.='</td></tr></table>' };
 1033:     return $template;
 1034: 
 1035: }
 1036: 
 1037: sub help_open_faq {
 1038:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1039:     unless ($env{'user.adv'}) { return ''; }
 1040:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1041:     $text = "" if (not defined $text);
 1042:     $stayOnPage = 0 if (not defined $stayOnPage);
 1043:     if ($env{'browser.interface'} eq 'textual' ||
 1044: 	$env{'environment.remote'} eq 'off' ) {
 1045: 	$stayOnPage=1;
 1046:     }
 1047:     $width = 350 if (not defined $width);
 1048:     $height = 400 if (not defined $height);
 1049: 
 1050:     $topic=~s/\W+/\+/g;
 1051:     my $link='';
 1052:     my $template='';
 1053:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1054:     if (!$stayOnPage)
 1055:     {
 1056: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1057:     }
 1058:     else
 1059:     {
 1060: 	$link = $url;
 1061:     }
 1062: 
 1063:     # Add the text
 1064:     if ($text ne "")
 1065:     {
 1066: 	$template .= 
 1067:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1068:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1069:     }
 1070: 
 1071:     # Add the graphic
 1072:     my $title = &mt('View the FAQ');
 1073:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1074:     $template .= <<"ENDTEMPLATE";
 1075:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1076: ENDTEMPLATE
 1077:     if ($text ne '') { $template.='</td></tr></table>' };
 1078:     return $template;
 1079: 
 1080: }
 1081: 
 1082: ###############################################################
 1083: ###############################################################
 1084: 
 1085: =pod
 1086: 
 1087: =item * &change_content_javascript():
 1088: 
 1089: This and the next function allow you to create small sections of an
 1090: otherwise static HTML page that you can update on the fly with
 1091: Javascript, even in Netscape 4.
 1092: 
 1093: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1094: must be written to the HTML page once. It will prove the Javascript
 1095: function "change(name, content)". Calling the change function with the
 1096: name of the section 
 1097: you want to update, matching the name passed to C<changable_area>, and
 1098: the new content you want to put in there, will put the content into
 1099: that area.
 1100: 
 1101: B<Note>: Netscape 4 only reserves enough space for the changable area
 1102: to contain room for the original contents. You need to "make space"
 1103: for whatever changes you wish to make, and be B<sure> to check your
 1104: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1105: it's adequate for updating a one-line status display, but little more.
 1106: This script will set the space to 100% width, so you only need to
 1107: worry about height in Netscape 4.
 1108: 
 1109: Modern browsers are much less limiting, and if you can commit to the
 1110: user not using Netscape 4, this feature may be used freely with
 1111: pretty much any HTML.
 1112: 
 1113: =cut
 1114: 
 1115: sub change_content_javascript {
 1116:     # If we're on Netscape 4, we need to use Layer-based code
 1117:     if ($env{'browser.type'} eq 'netscape' &&
 1118: 	$env{'browser.version'} =~ /^4\./) {
 1119: 	return (<<NETSCAPE4);
 1120: 	function change(name, content) {
 1121: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1122: 	    doc.open();
 1123: 	    doc.write(content);
 1124: 	    doc.close();
 1125: 	}
 1126: NETSCAPE4
 1127:     } else {
 1128: 	# Otherwise, we need to use semi-standards-compliant code
 1129: 	# (technically, "innerHTML" isn't standard but the equivalent
 1130: 	# is really scary, and every useful browser supports it
 1131: 	return (<<DOMBASED);
 1132: 	function change(name, content) {
 1133: 	    element = document.getElementById(name);
 1134: 	    element.innerHTML = content;
 1135: 	}
 1136: DOMBASED
 1137:     }
 1138: }
 1139: 
 1140: =pod
 1141: 
 1142: =item * &changable_area($name,$origContent):
 1143: 
 1144: This provides a "changable area" that can be modified on the fly via
 1145: the Javascript code provided in C<change_content_javascript>. $name is
 1146: the name you will use to reference the area later; do not repeat the
 1147: same name on a given HTML page more then once. $origContent is what
 1148: the area will originally contain, which can be left blank.
 1149: 
 1150: =cut
 1151: 
 1152: sub changable_area {
 1153:     my ($name, $origContent) = @_;
 1154: 
 1155:     if ($env{'browser.type'} eq 'netscape' &&
 1156: 	$env{'browser.version'} =~ /^4\./) {
 1157: 	# If this is netscape 4, we need to use the Layer tag
 1158: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1159:     } else {
 1160: 	return "<span id='$name'>$origContent</span>";
 1161:     }
 1162: }
 1163: 
 1164: =pod
 1165: 
 1166: =item * &viewport_geometry_js 
 1167: 
 1168: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1169: 
 1170: =cut
 1171: 
 1172: 
 1173: sub viewport_geometry_js { 
 1174:     return <<"GEOMETRY";
 1175: var Geometry = {};
 1176: function init_geometry() {
 1177:     if (Geometry.init) { return };
 1178:     Geometry.init=1;
 1179:     if (window.innerHeight) {
 1180:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1181:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1182:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1183:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1184:     }
 1185:     else if (document.documentElement && document.documentElement.clientHeight) {
 1186:         Geometry.getViewportHeight =
 1187:             function() { return document.documentElement.clientHeight; };
 1188:         Geometry.getViewportWidth =
 1189:             function() { return document.documentElement.clientWidth; };
 1190: 
 1191:         Geometry.getHorizontalScroll =
 1192:             function() { return document.documentElement.scrollLeft; };
 1193:         Geometry.getVerticalScroll =
 1194:             function() { return document.documentElement.scrollTop; };
 1195:     }
 1196:     else if (document.body.clientHeight) {
 1197:         Geometry.getViewportHeight =
 1198:             function() { return document.body.clientHeight; };
 1199:         Geometry.getViewportWidth =
 1200:             function() { return document.body.clientWidth; };
 1201:         Geometry.getHorizontalScroll =
 1202:             function() { return document.body.scrollLeft; };
 1203:         Geometry.getVerticalScroll =
 1204:             function() { return document.body.scrollTop; };
 1205:     }
 1206: }
 1207: 
 1208: GEOMETRY
 1209: }
 1210: 
 1211: =pod
 1212: 
 1213: =item * &viewport_size_js()
 1214: 
 1215: 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. 
 1216: 
 1217: =cut
 1218: 
 1219: sub viewport_size_js {
 1220:     my $geometry = &viewport_geometry_js();
 1221:     return <<"DIMS";
 1222: 
 1223: $geometry
 1224: 
 1225: function getViewportDims(width,height) {
 1226:     init_geometry();
 1227:     width.value = Geometry.getViewportWidth();
 1228:     height.value = Geometry.getViewportHeight();
 1229:     return;
 1230: }
 1231: 
 1232: DIMS
 1233: }
 1234: 
 1235: =pod
 1236: 
 1237: =item * &resize_textarea_js()
 1238: 
 1239: emits the needed javascript to resize a textarea to be as big as possible
 1240: 
 1241: creates a function resize_textrea that takes two IDs first should be
 1242: the id of the element to resize, second should be the id of a div that
 1243: surrounds everything that comes after the textarea, this routine needs
 1244: to be attached to the <body> for the onload and onresize events.
 1245: 
 1246: =back
 1247: 
 1248: =cut
 1249: 
 1250: sub resize_textarea_js {
 1251:     my $geometry = &viewport_geometry_js();
 1252:     return <<"RESIZE";
 1253:     <script type="text/javascript">
 1254: $geometry
 1255: 
 1256: function getX(element) {
 1257:     var x = 0;
 1258:     while (element) {
 1259: 	x += element.offsetLeft;
 1260: 	element = element.offsetParent;
 1261:     }
 1262:     return x;
 1263: }
 1264: function getY(element) {
 1265:     var y = 0;
 1266:     while (element) {
 1267: 	y += element.offsetTop;
 1268: 	element = element.offsetParent;
 1269:     }
 1270:     return y;
 1271: }
 1272: 
 1273: 
 1274: function resize_textarea(textarea_id,bottom_id) {
 1275:     init_geometry();
 1276:     var textarea        = document.getElementById(textarea_id);
 1277:     //alert(textarea);
 1278: 
 1279:     var textarea_top    = getY(textarea);
 1280:     var textarea_height = textarea.offsetHeight;
 1281:     var bottom          = document.getElementById(bottom_id);
 1282:     var bottom_top      = getY(bottom);
 1283:     var bottom_height   = bottom.offsetHeight;
 1284:     var window_height   = Geometry.getViewportHeight();
 1285:     var fudge           = 23;
 1286:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1287:     if (new_height < 300) {
 1288: 	new_height = 300;
 1289:     }
 1290:     textarea.style.height=new_height+'px';
 1291: }
 1292: </script>
 1293: RESIZE
 1294: 
 1295: }
 1296: 
 1297: =pod
 1298: 
 1299: =head1 Excel and CSV file utility routines
 1300: 
 1301: =over 4
 1302: 
 1303: =cut
 1304: 
 1305: ###############################################################
 1306: ###############################################################
 1307: 
 1308: =pod
 1309: 
 1310: =item * &csv_translate($text) 
 1311: 
 1312: Translate $text to allow it to be output as a 'comma separated values' 
 1313: format.
 1314: 
 1315: =cut
 1316: 
 1317: ###############################################################
 1318: ###############################################################
 1319: sub csv_translate {
 1320:     my $text = shift;
 1321:     $text =~ s/\"/\"\"/g;
 1322:     $text =~ s/\n/ /g;
 1323:     return $text;
 1324: }
 1325: 
 1326: ###############################################################
 1327: ###############################################################
 1328: 
 1329: =pod
 1330: 
 1331: =item * &define_excel_formats()
 1332: 
 1333: Define some commonly used Excel cell formats.
 1334: 
 1335: Currently supported formats:
 1336: 
 1337: =over 4
 1338: 
 1339: =item header
 1340: 
 1341: =item bold
 1342: 
 1343: =item h1
 1344: 
 1345: =item h2
 1346: 
 1347: =item h3
 1348: 
 1349: =item h4
 1350: 
 1351: =item i
 1352: 
 1353: =item date
 1354: 
 1355: =back
 1356: 
 1357: Inputs: $workbook
 1358: 
 1359: Returns: $format, a hash reference.
 1360: 
 1361: =cut
 1362: 
 1363: ###############################################################
 1364: ###############################################################
 1365: sub define_excel_formats {
 1366:     my ($workbook) = @_;
 1367:     my $format;
 1368:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1369:                                                 bottom    => 1,
 1370:                                                 align     => 'center');
 1371:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1372:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1373:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1374:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1375:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1376:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1377:     $format->{'date'} = $workbook->add_format(num_format=>
 1378:                                             'mm/dd/yyyy hh:mm:ss');
 1379:     return $format;
 1380: }
 1381: 
 1382: ###############################################################
 1383: ###############################################################
 1384: 
 1385: =pod
 1386: 
 1387: =item * &create_workbook()
 1388: 
 1389: Create an Excel worksheet.  If it fails, output message on the
 1390: request object and return undefs.
 1391: 
 1392: Inputs: Apache request object
 1393: 
 1394: Returns (undef) on failure, 
 1395:     Excel worksheet object, scalar with filename, and formats 
 1396:     from &Apache::loncommon::define_excel_formats on success
 1397: 
 1398: =cut
 1399: 
 1400: ###############################################################
 1401: ###############################################################
 1402: sub create_workbook {
 1403:     my ($r) = @_;
 1404:         #
 1405:     # Create the excel spreadsheet
 1406:     my $filename = '/prtspool/'.
 1407:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1408:         time.'_'.rand(1000000000).'.xls';
 1409:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1410:     if (! defined($workbook)) {
 1411:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1412:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1413:                             "This error has been logged.  ".
 1414:                             "Please alert your LON-CAPA administrator").
 1415:                   '</p>');
 1416:         return (undef);
 1417:     }
 1418:     #
 1419:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1420:     #
 1421:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1422:     return ($workbook,$filename,$format);
 1423: }
 1424: 
 1425: ###############################################################
 1426: ###############################################################
 1427: 
 1428: =pod
 1429: 
 1430: =item * &create_text_file()
 1431: 
 1432: Create a file to write to and eventually make available to the user.
 1433: If file creation fails, outputs an error message on the request object and 
 1434: return undefs.
 1435: 
 1436: Inputs: Apache request object, and file suffix
 1437: 
 1438: Returns (undef) on failure, 
 1439:     Filehandle and filename on success.
 1440: 
 1441: =cut
 1442: 
 1443: ###############################################################
 1444: ###############################################################
 1445: sub create_text_file {
 1446:     my ($r,$suffix) = @_;
 1447:     if (! defined($suffix)) { $suffix = 'txt'; };
 1448:     my $fh;
 1449:     my $filename = '/prtspool/'.
 1450:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1451:         time.'_'.rand(1000000000).'.'.$suffix;
 1452:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1453:     if (! defined($fh)) {
 1454:         $r->log_error("Couldn't open $filename for output $!");
 1455:         $r->print("Problems occured in creating the output file.  ".
 1456:                   "This error has been logged.  ".
 1457:                   "Please alert your LON-CAPA administrator.");
 1458:     }
 1459:     return ($fh,$filename)
 1460: }
 1461: 
 1462: 
 1463: =pod 
 1464: 
 1465: =back
 1466: 
 1467: =cut
 1468: 
 1469: ###############################################################
 1470: ##        Home server <option> list generating code          ##
 1471: ###############################################################
 1472: 
 1473: # ------------------------------------------
 1474: 
 1475: sub domain_select {
 1476:     my ($name,$value,$multiple)=@_;
 1477:     my %domains=map { 
 1478: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1479:     } &Apache::lonnet::all_domains();
 1480:     if ($multiple) {
 1481: 	$domains{''}=&mt('Any domain');
 1482: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1483: 	return &multiple_select_form($name,$value,4,\%domains);
 1484:     } else {
 1485: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1486: 	return &select_form($name,$value,%domains);
 1487:     }
 1488: }
 1489: 
 1490: #-------------------------------------------
 1491: 
 1492: =pod
 1493: 
 1494: =head1 Routines for form select boxes
 1495: 
 1496: =over 4
 1497: 
 1498: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1499: 
 1500: Returns a string containing a <select> element int multiple mode
 1501: 
 1502: 
 1503: Args:
 1504:   $name - name of the <select> element
 1505:   $value - scalar or array ref of values that should already be selected
 1506:   $size - number of rows long the select element is
 1507:   $hash - the elements should be 'option' => 'shown text'
 1508:           (shown text should already have been &mt())
 1509:   $order - (optional) array ref of the order to show the elements in
 1510: 
 1511: =cut
 1512: 
 1513: #-------------------------------------------
 1514: sub multiple_select_form {
 1515:     my ($name,$value,$size,$hash,$order)=@_;
 1516:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1517:     my $output='';
 1518:     if (! defined($size)) {
 1519:         $size = 4;
 1520:         if (scalar(keys(%$hash))<4) {
 1521:             $size = scalar(keys(%$hash));
 1522:         }
 1523:     }
 1524:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1525:     my @order;
 1526:     if (ref($order) eq 'ARRAY')  {
 1527:         @order = @{$order};
 1528:     } else {
 1529:         @order = sort(keys(%$hash));
 1530:     }
 1531:     if (exists($$hash{'select_form_order'})) {
 1532:         @order = @{$$hash{'select_form_order'}};
 1533:     }
 1534:         
 1535:     foreach my $key (@order) {
 1536:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1537:         $output.='selected="selected" ' if ($selected{$key});
 1538:         $output.='>'.$hash->{$key}."</option>\n";
 1539:     }
 1540:     $output.="</select>\n";
 1541:     return $output;
 1542: }
 1543: 
 1544: #-------------------------------------------
 1545: 
 1546: =pod
 1547: 
 1548: =item * &select_form($defdom,$name,%hash)
 1549: 
 1550: Returns a string containing a <select name='$name' size='1'> form to 
 1551: allow a user to select options from a hash option_name => displayed text.  
 1552: See lonrights.pm for an example invocation and use.
 1553: 
 1554: =cut
 1555: 
 1556: #-------------------------------------------
 1557: sub select_form {
 1558:     my ($def,$name,%hash) = @_;
 1559:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1560:     my @keys;
 1561:     if (exists($hash{'select_form_order'})) {
 1562: 	@keys=@{$hash{'select_form_order'}};
 1563:     } else {
 1564: 	@keys=sort(keys(%hash));
 1565:     }
 1566:     foreach my $key (@keys) {
 1567:         $selectform.=
 1568: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1569:             ($key eq $def ? 'selected="selected" ' : '').
 1570:                 ">".&mt($hash{$key})."</option>\n";
 1571:     }
 1572:     $selectform.="</select>";
 1573:     return $selectform;
 1574: }
 1575: 
 1576: # For display filters
 1577: 
 1578: sub display_filter {
 1579:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1580:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1581:     return '<nobr><label>'.&mt('Records [_1]',
 1582: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1583: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1584: 	   '</label></nobr> <nobr>'.
 1585:            &mt('Filter [_1]',
 1586: 	   &select_form($env{'form.displayfilter'},
 1587: 			'displayfilter',
 1588: 			('currentfolder' => 'Current folder/page',
 1589: 			 'containing' => 'Containing phrase',
 1590: 			 'none' => 'None'))).
 1591: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
 1592: }
 1593: 
 1594: sub gradeleveldescription {
 1595:     my $gradelevel=shift;
 1596:     my %gradelevels=(0 => 'Not specified',
 1597: 		     1 => 'Grade 1',
 1598: 		     2 => 'Grade 2',
 1599: 		     3 => 'Grade 3',
 1600: 		     4 => 'Grade 4',
 1601: 		     5 => 'Grade 5',
 1602: 		     6 => 'Grade 6',
 1603: 		     7 => 'Grade 7',
 1604: 		     8 => 'Grade 8',
 1605: 		     9 => 'Grade 9',
 1606: 		     10 => 'Grade 10',
 1607: 		     11 => 'Grade 11',
 1608: 		     12 => 'Grade 12',
 1609: 		     13 => 'Grade 13',
 1610: 		     14 => '100 Level',
 1611: 		     15 => '200 Level',
 1612: 		     16 => '300 Level',
 1613: 		     17 => '400 Level',
 1614: 		     18 => 'Graduate Level');
 1615:     return &mt($gradelevels{$gradelevel});
 1616: }
 1617: 
 1618: sub select_level_form {
 1619:     my ($deflevel,$name)=@_;
 1620:     unless ($deflevel) { $deflevel=0; }
 1621:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1622:     for (my $i=0; $i<=18; $i++) {
 1623:         $selectform.="<option value=\"$i\" ".
 1624:             ($i==$deflevel ? 'selected="selected" ' : '').
 1625:                 ">".&gradeleveldescription($i)."</option>\n";
 1626:     }
 1627:     $selectform.="</select>";
 1628:     return $selectform;
 1629: }
 1630: 
 1631: #-------------------------------------------
 1632: 
 1633: =pod
 1634: 
 1635: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
 1636: 
 1637: Returns a string containing a <select name='$name' size='1'> form to 
 1638: allow a user to select the domain to preform an operation in.  
 1639: See loncreateuser.pm for an example invocation and use.
 1640: 
 1641: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1642: selected");
 1643: 
 1644: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
 1645: 
 1646: =cut
 1647: 
 1648: #-------------------------------------------
 1649: sub select_dom_form {
 1650:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
 1651:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1652:     if ($includeempty) { @domains=('',@domains); }
 1653:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1654:     foreach my $dom (@domains) {
 1655:         $selectdomain.="<option value=\"$dom\" ".
 1656:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1657:         if ($showdomdesc) {
 1658:             if ($dom ne '') {
 1659:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1660:                 if ($domdesc ne '') {
 1661:                     $selectdomain .= ' ('.$domdesc.')';
 1662:                 }
 1663:             } 
 1664:         }
 1665:         $selectdomain .= "</option>\n";
 1666:     }
 1667:     $selectdomain.="</select>";
 1668:     return $selectdomain;
 1669: }
 1670: 
 1671: #-------------------------------------------
 1672: 
 1673: =pod
 1674: 
 1675: =item * &home_server_form_item($domain,$name,$defaultflag)
 1676: 
 1677: input: 4 arguments (two required, two optional) - 
 1678:     $domain - domain of new user
 1679:     $name - name of form element
 1680:     $default - Value of 'default' causes a default item to be first 
 1681:                             option, and selected by default. 
 1682:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1683:                             if 1 server found, or default, if 0 found.
 1684: output: returns 2 items: 
 1685: (a) form element which contains either:
 1686:    (i) <select name="$name">
 1687:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1688:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1689:        </select>
 1690:        form item if there are multiple library servers in $domain, or
 1691:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1692:        if there is only one library server in $domain.
 1693: 
 1694: (b) number of library servers found.
 1695: 
 1696: See loncreateuser.pm for example of use.
 1697: 
 1698: =cut
 1699: 
 1700: #-------------------------------------------
 1701: sub home_server_form_item {
 1702:     my ($domain,$name,$default,$hide) = @_;
 1703:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1704:     my $result;
 1705:     my $numlib = keys(%servers);
 1706:     if ($numlib > 1) {
 1707:         $result .= '<select name="'.$name.'" />'."\n";
 1708:         if ($default) {
 1709:             $result .= '<option value="default" selected>'.&mt('default').
 1710:                        '</option>'."\n";
 1711:         }
 1712:         foreach my $hostid (sort(keys(%servers))) {
 1713:             $result.= '<option value="'.$hostid.'">'.
 1714: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1715:         }
 1716:         $result .= '</select>'."\n";
 1717:     } elsif ($numlib == 1) {
 1718:         my $hostid;
 1719:         foreach my $item (keys(%servers)) {
 1720:             $hostid = $item;
 1721:         }
 1722:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1723:                    $hostid.'" />';
 1724:                    if (!$hide) {
 1725:                        $result .= $hostid.' '.$servers{$hostid};
 1726:                    }
 1727:                    $result .= "\n";
 1728:     } elsif ($default) {
 1729:         $result .= '<input type="hidden" name="'.$name.
 1730:                    '" value="default" />';
 1731:                    if (!$hide) {
 1732:                        $result .= &mt('default');
 1733:                    }
 1734:                    $result .= "\n";
 1735:     }
 1736:     return ($result,$numlib);
 1737: }
 1738: 
 1739: =pod
 1740: 
 1741: =back 
 1742: 
 1743: =cut
 1744: 
 1745: ###############################################################
 1746: ##                  Decoding User Agent                      ##
 1747: ###############################################################
 1748: 
 1749: =pod
 1750: 
 1751: =head1 Decoding the User Agent
 1752: 
 1753: =over 4
 1754: 
 1755: =item * &decode_user_agent()
 1756: 
 1757: Inputs: $r
 1758: 
 1759: Outputs:
 1760: 
 1761: =over 4
 1762: 
 1763: =item * $httpbrowser
 1764: 
 1765: =item * $clientbrowser
 1766: 
 1767: =item * $clientversion
 1768: 
 1769: =item * $clientmathml
 1770: 
 1771: =item * $clientunicode
 1772: 
 1773: =item * $clientos
 1774: 
 1775: =back
 1776: 
 1777: =back 
 1778: 
 1779: =cut
 1780: 
 1781: ###############################################################
 1782: ###############################################################
 1783: sub decode_user_agent {
 1784:     my ($r)=@_;
 1785:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1786:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1787:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1788:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1789:     my $clientbrowser='unknown';
 1790:     my $clientversion='0';
 1791:     my $clientmathml='';
 1792:     my $clientunicode='0';
 1793:     for (my $i=0;$i<=$#browsertype;$i++) {
 1794:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1795: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1796: 	    $clientbrowser=$bname;
 1797:             $httpbrowser=~/$vreg/i;
 1798: 	    $clientversion=$1;
 1799:             $clientmathml=($clientversion>=$minv);
 1800:             $clientunicode=($clientversion>=$univ);
 1801: 	}
 1802:     }
 1803:     my $clientos='unknown';
 1804:     if (($httpbrowser=~/linux/i) ||
 1805:         ($httpbrowser=~/unix/i) ||
 1806:         ($httpbrowser=~/ux/i) ||
 1807:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1808:     if (($httpbrowser=~/vax/i) ||
 1809:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1810:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1811:     if (($httpbrowser=~/mac/i) ||
 1812:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1813:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1814:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1815:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1816:             $clientunicode,$clientos,);
 1817: }
 1818: 
 1819: ###############################################################
 1820: ##    Authentication changing form generation subroutines    ##
 1821: ###############################################################
 1822: ##
 1823: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1824: ## hash, and have reasonable default values.
 1825: ##
 1826: ##    formname = the name given in the <form> tag.
 1827: #-------------------------------------------
 1828: 
 1829: =pod
 1830: 
 1831: =head1 Authentication Routines
 1832: 
 1833: =over 4
 1834: 
 1835: =item * &authform_xxxxxx()
 1836: 
 1837: The authform_xxxxxx subroutines provide javascript and html forms which 
 1838: handle some of the conveniences required for authentication forms.  
 1839: This is not an optimal method, but it works.  
 1840: 
 1841: =over 4
 1842: 
 1843: =item * authform_header
 1844: 
 1845: =item * authform_authorwarning
 1846: 
 1847: =item * authform_nochange
 1848: 
 1849: =item * authform_kerberos
 1850: 
 1851: =item * authform_internal
 1852: 
 1853: =item * authform_filesystem
 1854: 
 1855: =back
 1856: 
 1857: See loncreateuser.pm for invocation and use examples.
 1858: 
 1859: =cut
 1860: 
 1861: #-------------------------------------------
 1862: sub authform_header{  
 1863:     my %in = (
 1864:         formname => 'cu',
 1865:         kerb_def_dom => '',
 1866:         @_,
 1867:     );
 1868:     $in{'formname'} = 'document.' . $in{'formname'};
 1869:     my $result='';
 1870: 
 1871: #---------------------------------------------- Code for upper case translation
 1872:     my $Javascript_toUpperCase;
 1873:     unless ($in{kerb_def_dom}) {
 1874:         $Javascript_toUpperCase =<<"END";
 1875:         switch (choice) {
 1876:            case 'krb': currentform.elements[choicearg].value =
 1877:                currentform.elements[choicearg].value.toUpperCase();
 1878:                break;
 1879:            default:
 1880:         }
 1881: END
 1882:     } else {
 1883:         $Javascript_toUpperCase = "";
 1884:     }
 1885: 
 1886:     my $radioval = "'nochange'";
 1887:     if (defined($in{'curr_authtype'})) {
 1888:         if ($in{'curr_authtype'} ne '') {
 1889:             $radioval = "'".$in{'curr_authtype'}."arg'";
 1890:         }
 1891:     }
 1892:     my $argfield = 'null';
 1893:     if (defined($in{'mode'})) {
 1894:         if ($in{'mode'} eq 'modifycourse')  {
 1895:             if (defined($in{'curr_autharg'})) {
 1896:                 if ($in{'curr_autharg'} ne '') {
 1897:                     $argfield = "'$in{'curr_autharg'}'";
 1898:                 }
 1899:             }
 1900:         }
 1901:     }
 1902: 
 1903:     $result.=<<"END";
 1904: var current = new Object();
 1905: current.radiovalue = $radioval;
 1906: current.argfield = $argfield;
 1907: 
 1908: function changed_radio(choice,currentform) {
 1909:     var choicearg = choice + 'arg';
 1910:     // If a radio button in changed, we need to change the argfield
 1911:     if (current.radiovalue != choice) {
 1912:         current.radiovalue = choice;
 1913:         if (current.argfield != null) {
 1914:             currentform.elements[current.argfield].value = '';
 1915:         }
 1916:         if (choice == 'nochange') {
 1917:             current.argfield = null;
 1918:         } else {
 1919:             current.argfield = choicearg;
 1920:             switch(choice) {
 1921:                 case 'krb': 
 1922:                     currentform.elements[current.argfield].value = 
 1923:                         "$in{'kerb_def_dom'}";
 1924:                 break;
 1925:               default:
 1926:                 break;
 1927:             }
 1928:         }
 1929:     }
 1930:     return;
 1931: }
 1932: 
 1933: function changed_text(choice,currentform) {
 1934:     var choicearg = choice + 'arg';
 1935:     if (currentform.elements[choicearg].value !='') {
 1936:         $Javascript_toUpperCase
 1937:         // clear old field
 1938:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1939:             currentform.elements[current.argfield].value = '';
 1940:         }
 1941:         current.argfield = choicearg;
 1942:     }
 1943:     set_auth_radio_buttons(choice,currentform);
 1944:     return;
 1945: }
 1946: 
 1947: function set_auth_radio_buttons(newvalue,currentform) {
 1948:     var i=0;
 1949:     while (i < currentform.login.length) {
 1950:         if (currentform.login[i].value == newvalue) { break; }
 1951:         i++;
 1952:     }
 1953:     if (i == currentform.login.length) {
 1954:         return;
 1955:     }
 1956:     current.radiovalue = newvalue;
 1957:     currentform.login[i].checked = true;
 1958:     return;
 1959: }
 1960: END
 1961:     return $result;
 1962: }
 1963: 
 1964: sub authform_authorwarning{
 1965:     my $result='';
 1966:     $result='<i>'.
 1967:         &mt('As a general rule, only authors or co-authors should be '.
 1968:             'filesystem authenticated '.
 1969:             '(which allows access to the server filesystem).')."</i>\n";
 1970:     return $result;
 1971: }
 1972: 
 1973: sub authform_nochange{  
 1974:     my %in = (
 1975:               formname => 'document.cu',
 1976:               kerb_def_dom => 'MSU.EDU',
 1977:               @_,
 1978:           );
 1979:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 1980:     my $result;
 1981:     if (keys(%can_assign) == 0) {
 1982:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 1983:     } else {
 1984:         $result = '<label>'.&mt('[_1] Do not change login data',
 1985:                   '<input type="radio" name="login" value="nochange" '.
 1986:                   'checked="checked" onclick="'.
 1987:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 1988: 	    '</label>';
 1989:     }
 1990:     return $result;
 1991: }
 1992: 
 1993: sub authform_kerberos {
 1994:     my %in = (
 1995:               formname => 'document.cu',
 1996:               kerb_def_dom => 'MSU.EDU',
 1997:               kerb_def_auth => 'krb4',
 1998:               @_,
 1999:               );
 2000:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2001:         $autharg,$jscall);
 2002:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2003:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2004:        $check5 = ' checked="on"';
 2005:     } else {
 2006:        $check4 = ' checked="on"';
 2007:     }
 2008:     $krbarg = $in{'kerb_def_dom'};
 2009:     if (defined($in{'curr_authtype'})) {
 2010:         if ($in{'curr_authtype'} eq 'krb') {
 2011:             $krbcheck = ' checked="on"';
 2012:             if (defined($in{'mode'})) {
 2013:                 if ($in{'mode'} eq 'modifyuser') {
 2014:                     $krbcheck = '';
 2015:                 }
 2016:             }
 2017:             if (defined($in{'curr_kerb_ver'})) {
 2018:                 if ($in{'curr_krb_ver'} eq '5') {
 2019:                     $check5 = ' checked="on"';
 2020:                     $check4 = '';
 2021:                 } else {
 2022:                     $check4 = ' checked="on"';
 2023:                     $check5 = '';
 2024:                 }
 2025:             }
 2026:             if (defined($in{'curr_autharg'})) {
 2027:                 $krbarg = $in{'curr_autharg'};
 2028:             }
 2029:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2030:                 if (defined($in{'curr_autharg'})) {
 2031:                     $result = 
 2032:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2033:         $in{'curr_autharg'},$krbver);
 2034:                 } else {
 2035:                     $result =
 2036:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2037:                 }
 2038:                 return $result; 
 2039:             }
 2040:         }
 2041:     } else {
 2042:         if ($authnum == 1) {
 2043:             $authtype = '<input type="hidden" name="login" value="krb">';
 2044:         }
 2045:     }
 2046:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2047:         return;
 2048:     } elsif ($authtype eq '') {
 2049:         if (defined($in{'mode'})) {
 2050:             if ($in{'mode'} eq 'modifycourse') {
 2051:                 if ($authnum == 1) {
 2052:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2053:                 }
 2054:             }
 2055:         }
 2056:     }
 2057:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2058:     if ($authtype eq '') {
 2059:         $authtype = '<input type="radio" name="login" value="krb" '.
 2060:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2061:                     $krbcheck.' />';
 2062:     }
 2063:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2064:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2065:          $in{'curr_authtype'} eq 'krb5') ||
 2066:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2067:          $in{'curr_authtype'} eq 'krb4')) {
 2068:         $result .= &mt
 2069:         ('[_1] Kerberos authenticated with domain [_2] '.
 2070:          '[_3] Version 4 [_4] Version 5 [_5]',
 2071:          '<label>'.$authtype,
 2072:          '</label><input type="text" size="10" name="krbarg" '.
 2073:              'value="'.$krbarg.'" '.
 2074:              'onchange="'.$jscall.'" />',
 2075:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2076:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2077: 	 '</label>');
 2078:     } elsif ($can_assign{'krb4'}) {
 2079:         $result .= &mt
 2080:         ('[_1] Kerberos authenticated with domain [_2] '.
 2081:          '[_3] Version 4 [_4]',
 2082:          '<label>'.$authtype,
 2083:          '</label><input type="text" size="10" name="krbarg" '.
 2084:              'value="'.$krbarg.'" '.
 2085:              'onchange="'.$jscall.'" />',
 2086:          '<label><input type="hidden" name="krbver" value="4" />',
 2087:          '</label>');
 2088:     } elsif ($can_assign{'krb5'}) {
 2089:         $result .= &mt
 2090:         ('[_1] Kerberos authenticated with domain [_2] '.
 2091:          '[_3] Version 5 [_4]',
 2092:          '<label>'.$authtype,
 2093:          '</label><input type="text" size="10" name="krbarg" '.
 2094:              'value="'.$krbarg.'" '.
 2095:              'onchange="'.$jscall.'" />',
 2096:          '<label><input type="hidden" name="krbver" value="5" />',
 2097:          '</label>');
 2098:     }
 2099:     return $result;
 2100: }
 2101: 
 2102: sub authform_internal{  
 2103:     my %in = (
 2104:                 formname => 'document.cu',
 2105:                 kerb_def_dom => 'MSU.EDU',
 2106:                 @_,
 2107:                 );
 2108:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2109:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2110:     if (defined($in{'curr_authtype'})) {
 2111:         if ($in{'curr_authtype'} eq 'int') {
 2112:             if ($can_assign{'int'}) {
 2113:                 $intcheck = 'checked="on" ';
 2114:                 if (defined($in{'mode'})) {
 2115:                     if ($in{'mode'} eq 'modifyuser') {
 2116:                         $intcheck = '';
 2117:                     }
 2118:                 }
 2119:                 if (defined($in{'curr_autharg'})) {
 2120:                     $intarg = $in{'curr_autharg'};
 2121:                 }
 2122:             } else {
 2123:                 $result = &mt('Currently internally authenticated.');
 2124:                 return $result;
 2125:             }
 2126:         }
 2127:     } else {
 2128:         if ($authnum == 1) {
 2129:             $authtype = '<input type="hidden" name="login" value="int">';
 2130:         }
 2131:     }
 2132:     if (!$can_assign{'int'}) {
 2133:         return;
 2134:     } elsif ($authtype eq '') {
 2135:         if (defined($in{'mode'})) {
 2136:             if ($in{'mode'} eq 'modifycourse') {
 2137:                 if ($authnum == 1) {
 2138:                     $authtype = '<input type="hidden" name="login" value="int">';
 2139:                 }
 2140:             }
 2141:         }
 2142:     }
 2143:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2144:     if ($authtype eq '') {
 2145:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2146:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2147:     }
 2148:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2149:                $intarg.'" onchange="'.$jscall.'" />';
 2150:     $result = &mt
 2151:         ('[_1] Internally authenticated (with initial password [_2])',
 2152:          '<label>'.$authtype,'</label>'.$autharg);
 2153:     $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>';
 2154:     return $result;
 2155: }
 2156: 
 2157: sub authform_local{  
 2158:     my %in = (
 2159:               formname => 'document.cu',
 2160:               kerb_def_dom => 'MSU.EDU',
 2161:               @_,
 2162:               );
 2163:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2164:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2165:     if (defined($in{'curr_authtype'})) {
 2166:         if ($in{'curr_authtype'} eq 'loc') {
 2167:             if ($can_assign{'loc'}) {
 2168:                 $loccheck = 'checked="on" ';
 2169:                 if (defined($in{'mode'})) {
 2170:                     if ($in{'mode'} eq 'modifyuser') {
 2171:                         $loccheck = '';
 2172:                     }
 2173:                 }
 2174:                 if (defined($in{'curr_autharg'})) {
 2175:                     $locarg = $in{'curr_autharg'};
 2176:                 }
 2177:             } else {
 2178:                 $result = &mt('Currently using local (institutional) authentication.');
 2179:                 return $result;
 2180:             }
 2181:         }
 2182:     } else {
 2183:         if ($authnum == 1) {
 2184:             $authtype = '<input type="hidden" name="login" value="loc">';
 2185:         }
 2186:     }
 2187:     if (!$can_assign{'loc'}) {
 2188:         return;
 2189:     } elsif ($authtype eq '') {
 2190:         if (defined($in{'mode'})) {
 2191:             if ($in{'mode'} eq 'modifycourse') {
 2192:                 if ($authnum == 1) {
 2193:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2194:                 }
 2195:             }
 2196:         }
 2197:     }
 2198:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2199:     if ($authtype eq '') {
 2200:         $authtype = '<input type="radio" name="login" value="loc" '.
 2201:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2202:                     $jscall.'" />';
 2203:     }
 2204:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2205:                $locarg.'" onchange="'.$jscall.'" />';
 2206:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2207:                   '<label>'.$authtype,'</label>'.$autharg);
 2208:     return $result;
 2209: }
 2210: 
 2211: sub authform_filesystem{  
 2212:     my %in = (
 2213:               formname => 'document.cu',
 2214:               kerb_def_dom => 'MSU.EDU',
 2215:               @_,
 2216:               );
 2217:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2218:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2219:     if (defined($in{'curr_authtype'})) {
 2220:         if ($in{'curr_authtype'} eq 'fsys') {
 2221:             if ($can_assign{'fsys'}) {
 2222:                 $fsyscheck = 'checked="on" ';
 2223:                 if (defined($in{'mode'})) {
 2224:                     if ($in{'mode'} eq 'modifyuser') {
 2225:                         $fsyscheck = '';
 2226:                     }
 2227:                 }
 2228:             } else {
 2229:                 $result = &mt('Currently Filesystem Authenticated.');
 2230:                 return $result;
 2231:             }           
 2232:         }
 2233:     } else {
 2234:         if ($authnum == 1) {
 2235:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2236:         }
 2237:     }
 2238:     if (!$can_assign{'fsys'}) {
 2239:         return;
 2240:     } elsif ($authtype eq '') {
 2241:         if (defined($in{'mode'})) {
 2242:             if ($in{'mode'} eq 'modifycourse') {
 2243:                 if ($authnum == 1) {
 2244:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2245:                 }
 2246:             }
 2247:         }
 2248:     }
 2249:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2250:     if ($authtype eq '') {
 2251:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2252:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2253:                     $jscall.'" />';
 2254:     }
 2255:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2256:                ' onchange="'.$jscall.'" />';
 2257:     $result = &mt
 2258:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2259:          '<label><input type="radio" name="login" value="fsys" '.
 2260:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2261:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2262:                   'onchange="'.$jscall.'" />');
 2263:     return $result;
 2264: }
 2265: 
 2266: sub get_assignable_auth {
 2267:     my ($dom) = @_;
 2268:     if ($dom eq '') {
 2269:         $dom = $env{'request.role.domain'};
 2270:     }
 2271:     my %can_assign = (
 2272:                           krb4 => 1,
 2273:                           krb5 => 1,
 2274:                           int  => 1,
 2275:                           loc  => 1,
 2276:                      );
 2277:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2278:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2279:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2280:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2281:             my $context;
 2282:             if ($env{'request.role'} =~ /^au/) {
 2283:                 $context = 'author';
 2284:             } elsif ($env{'request.role'} =~ /^dc/) {
 2285:                 $context = 'domain';
 2286:             } elsif ($env{'request.course.id'}) {
 2287:                 $context = 'course';
 2288:             }
 2289:             if ($context) {
 2290:                 if (ref($authhash->{$context}) eq 'HASH') {
 2291:                    %can_assign = %{$authhash->{$context}}; 
 2292:                 }
 2293:             }
 2294:         }
 2295:     }
 2296:     my $authnum = 0;
 2297:     foreach my $key (keys(%can_assign)) {
 2298:         if ($can_assign{$key}) {
 2299:             $authnum ++;
 2300:         }
 2301:     }
 2302:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2303:         $authnum --;
 2304:     }
 2305:     return ($authnum,%can_assign);
 2306: }
 2307: 
 2308: ###############################################################
 2309: ##    Get Kerberos Defaults for Domain                 ##
 2310: ###############################################################
 2311: ##
 2312: ## Returns default kerberos version and an associated argument
 2313: ## as listed in file domain.tab. If not listed, provides
 2314: ## appropriate default domain and kerberos version.
 2315: ##
 2316: #-------------------------------------------
 2317: 
 2318: =pod
 2319: 
 2320: =item * &get_kerberos_defaults()
 2321: 
 2322: get_kerberos_defaults($target_domain) returns the default kerberos
 2323: version and domain. If not found, it defaults to version 4 and the 
 2324: domain of the server.
 2325: 
 2326: =over 4
 2327: 
 2328: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2329: 
 2330: =back
 2331: 
 2332: =back
 2333: 
 2334: =cut
 2335: 
 2336: #-------------------------------------------
 2337: sub get_kerberos_defaults {
 2338:     my $domain=shift;
 2339:     my ($krbdef,$krbdefdom);
 2340:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2341:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2342:         $krbdef = $domdefaults{'auth_def'};
 2343:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2344:     } else {
 2345:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2346:         my $krbdefdom=$1;
 2347:         $krbdefdom=~tr/a-z/A-Z/;
 2348:         $krbdef = "krb4";
 2349:     }
 2350:     return ($krbdef,$krbdefdom);
 2351: }
 2352: 
 2353: 
 2354: ###############################################################
 2355: ##                Thesaurus Functions                        ##
 2356: ###############################################################
 2357: 
 2358: =pod
 2359: 
 2360: =head1 Thesaurus Functions
 2361: 
 2362: =over 4
 2363: 
 2364: =item * &initialize_keywords()
 2365: 
 2366: Initializes the package variable %Keywords if it is empty.  Uses the
 2367: package variable $thesaurus_db_file.
 2368: 
 2369: =cut
 2370: 
 2371: ###################################################
 2372: 
 2373: sub initialize_keywords {
 2374:     return 1 if (scalar keys(%Keywords));
 2375:     # If we are here, %Keywords is empty, so fill it up
 2376:     #   Make sure the file we need exists...
 2377:     if (! -e $thesaurus_db_file) {
 2378:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2379:                                  " failed because it does not exist");
 2380:         return 0;
 2381:     }
 2382:     #   Set up the hash as a database
 2383:     my %thesaurus_db;
 2384:     if (! tie(%thesaurus_db,'GDBM_File',
 2385:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2386:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2387:                                  $thesaurus_db_file);
 2388:         return 0;
 2389:     } 
 2390:     #  Get the average number of appearances of a word.
 2391:     my $avecount = $thesaurus_db{'average.count'};
 2392:     #  Put keywords (those that appear > average) into %Keywords
 2393:     while (my ($word,$data)=each (%thesaurus_db)) {
 2394:         my ($count,undef) = split /:/,$data;
 2395:         $Keywords{$word}++ if ($count > $avecount);
 2396:     }
 2397:     untie %thesaurus_db;
 2398:     # Remove special values from %Keywords.
 2399:     foreach my $value ('total.count','average.count') {
 2400:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2401:   }
 2402:     return 1;
 2403: }
 2404: 
 2405: ###################################################
 2406: 
 2407: =pod
 2408: 
 2409: =item * &keyword($word)
 2410: 
 2411: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2412: than the average number of times in the thesaurus database.  Calls 
 2413: &initialize_keywords
 2414: 
 2415: =cut
 2416: 
 2417: ###################################################
 2418: 
 2419: sub keyword {
 2420:     return if (!&initialize_keywords());
 2421:     my $word=lc(shift());
 2422:     $word=~s/\W//g;
 2423:     return exists($Keywords{$word});
 2424: }
 2425: 
 2426: ###############################################################
 2427: 
 2428: =pod 
 2429: 
 2430: =item * &get_related_words()
 2431: 
 2432: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2433: an array of words.  If the keyword is not in the thesaurus, an empty array
 2434: will be returned.  The order of the words returned is determined by the
 2435: database which holds them.
 2436: 
 2437: Uses global $thesaurus_db_file.
 2438: 
 2439: =cut
 2440: 
 2441: ###############################################################
 2442: sub get_related_words {
 2443:     my $keyword = shift;
 2444:     my %thesaurus_db;
 2445:     if (! -e $thesaurus_db_file) {
 2446:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2447:                                  "failed because the file does not exist");
 2448:         return ();
 2449:     }
 2450:     if (! tie(%thesaurus_db,'GDBM_File',
 2451:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2452:         return ();
 2453:     } 
 2454:     my @Words=();
 2455:     my $count=0;
 2456:     if (exists($thesaurus_db{$keyword})) {
 2457: 	# The first element is the number of times
 2458: 	# the word appears.  We do not need it now.
 2459: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2460: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2461: 	my $threshold=$mostfrequentcount/10;
 2462:         foreach my $possibleword (@RelatedWords) {
 2463:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2464:             if ($wordcount>$threshold) {
 2465: 		push(@Words,$word);
 2466:                 $count++;
 2467:                 if ($count>10) { last; }
 2468: 	    }
 2469:         }
 2470:     }
 2471:     untie %thesaurus_db;
 2472:     return @Words;
 2473: }
 2474: 
 2475: =pod
 2476: 
 2477: =back
 2478: 
 2479: =cut
 2480: 
 2481: # -------------------------------------------------------------- Plaintext name
 2482: =pod
 2483: 
 2484: =head1 User Name Functions
 2485: 
 2486: =over 4
 2487: 
 2488: =item * &plainname($uname,$udom,$first)
 2489: 
 2490: Takes a users logon name and returns it as a string in
 2491: "first middle last generation" form 
 2492: if $first is set to 'lastname' then it returns it as
 2493: 'lastname generation, firstname middlename' if their is a lastname
 2494: 
 2495: =cut
 2496: 
 2497: 
 2498: ###############################################################
 2499: sub plainname {
 2500:     my ($uname,$udom,$first)=@_;
 2501:     return if (!defined($uname) || !defined($udom));
 2502:     my %names=&getnames($uname,$udom);
 2503:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2504: 					  $names{'middlename'},
 2505: 					  $names{'lastname'},
 2506: 					  $names{'generation'},$first);
 2507:     $name=~s/^\s+//;
 2508:     $name=~s/\s+$//;
 2509:     $name=~s/\s+/ /g;
 2510:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2511:     return $name;
 2512: }
 2513: 
 2514: # -------------------------------------------------------------------- Nickname
 2515: =pod
 2516: 
 2517: =item * &nickname($uname,$udom)
 2518: 
 2519: Gets a users name and returns it as a string as
 2520: 
 2521: "&quot;nickname&quot;"
 2522: 
 2523: if the user has a nickname or
 2524: 
 2525: "first middle last generation"
 2526: 
 2527: if the user does not
 2528: 
 2529: =cut
 2530: 
 2531: sub nickname {
 2532:     my ($uname,$udom)=@_;
 2533:     return if (!defined($uname) || !defined($udom));
 2534:     my %names=&getnames($uname,$udom);
 2535:     my $name=$names{'nickname'};
 2536:     if ($name) {
 2537:        $name='&quot;'.$name.'&quot;'; 
 2538:     } else {
 2539:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2540: 	     $names{'lastname'}.' '.$names{'generation'};
 2541:        $name=~s/\s+$//;
 2542:        $name=~s/\s+/ /g;
 2543:     }
 2544:     return $name;
 2545: }
 2546: 
 2547: sub getnames {
 2548:     my ($uname,$udom)=@_;
 2549:     return if (!defined($uname) || !defined($udom));
 2550:     if ($udom eq 'public' && $uname eq 'public') {
 2551: 	return ('lastname' => &mt('Public'));
 2552:     }
 2553:     my $id=$uname.':'.$udom;
 2554:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2555:     if ($cached) {
 2556: 	return %{$names};
 2557:     } else {
 2558: 	my %loadnames=&Apache::lonnet::get('environment',
 2559:                     ['firstname','middlename','lastname','generation','nickname'],
 2560: 					 $udom,$uname);
 2561: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2562: 	return %loadnames;
 2563:     }
 2564: }
 2565: 
 2566: # -------------------------------------------------------------------- getemails
 2567: 
 2568: =pod
 2569: 
 2570: =item * &getemails($uname,$udom)
 2571: 
 2572: Gets a user's email information and returns it as a hash with keys:
 2573: notification, critnotification, permanentemail
 2574: 
 2575: For notification and critnotification, values are comma-separated lists 
 2576: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2577:  
 2578: 
 2579: =cut
 2580: 
 2581: 
 2582: sub getemails {
 2583:     my ($uname,$udom)=@_;
 2584:     if ($udom eq 'public' && $uname eq 'public') {
 2585: 	return;
 2586:     }
 2587:     if (!$udom) { $udom=$env{'user.domain'}; }
 2588:     if (!$uname) { $uname=$env{'user.name'}; }
 2589:     my $id=$uname.':'.$udom;
 2590:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2591:     if ($cached) {
 2592: 	return %{$names};
 2593:     } else {
 2594: 	my %loadnames=&Apache::lonnet::get('environment',
 2595:                     			   ['notification','critnotification',
 2596: 					    'permanentemail'],
 2597: 					   $udom,$uname);
 2598: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2599: 	return %loadnames;
 2600:     }
 2601: }
 2602: 
 2603: sub flush_email_cache {
 2604:     my ($uname,$udom)=@_;
 2605:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2606:     if (!$uname) { $uname=$env{'user.name'};   }
 2607:     return if ($udom eq 'public' && $uname eq 'public');
 2608:     my $id=$uname.':'.$udom;
 2609:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2610: }
 2611: 
 2612: # ------------------------------------------------------------------ Screenname
 2613: 
 2614: =pod
 2615: 
 2616: =item * &screenname($uname,$udom)
 2617: 
 2618: Gets a users screenname and returns it as a string
 2619: 
 2620: =cut
 2621: 
 2622: sub screenname {
 2623:     my ($uname,$udom)=@_;
 2624:     if ($uname eq $env{'user.name'} &&
 2625: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2626:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2627:     return $names{'screenname'};
 2628: }
 2629: 
 2630: 
 2631: # ------------------------------------------------------------- Message Wrapper
 2632: 
 2633: sub messagewrapper {
 2634:     my ($link,$username,$domain,$subject,$text)=@_;
 2635:     return 
 2636:         '<a href="/adm/email?compose=individual&amp;'.
 2637:         'recname='.$username.'&amp;recdom='.$domain.
 2638: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2639:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2640: }
 2641: # --------------------------------------------------------------- Notes Wrapper
 2642: 
 2643: sub noteswrapper {
 2644:     my ($link,$un,$do)=@_;
 2645:     return 
 2646: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2647: }
 2648: # ------------------------------------------------------------- Aboutme Wrapper
 2649: 
 2650: sub aboutmewrapper {
 2651:     my ($link,$username,$domain,$target)=@_;
 2652:     if (!defined($username)  && !defined($domain)) {
 2653:         return;
 2654:     }
 2655:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2656: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2657: }
 2658: 
 2659: # ------------------------------------------------------------ Syllabus Wrapper
 2660: 
 2661: 
 2662: sub syllabuswrapper {
 2663:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2664:     if ($fontcolor) { 
 2665:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2666:     }
 2667:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2668: }
 2669: 
 2670: sub track_student_link {
 2671:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2672:     my $link ="/adm/trackstudent?";
 2673:     my $title = 'View recent activity';
 2674:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2675:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2676:         $link .= "selected_student=$sname:$sdom";
 2677:         $title .= ' of this student';
 2678:     } 
 2679:     if (defined($target) && $target !~ /^\s*$/) {
 2680:         $target = qq{target="$target"};
 2681:     } else {
 2682:         $target = '';
 2683:     }
 2684:     if ($start) { $link.='&amp;start='.$start; }
 2685:     $title = &mt($title);
 2686:     $linktext = &mt($linktext);
 2687:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2688: 	&help_open_topic('View_recent_activity');
 2689: }
 2690: 
 2691: # ===================================================== Display a student photo
 2692: 
 2693: 
 2694: sub student_image_tag {
 2695:     my ($domain,$user)=@_;
 2696:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2697:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2698: 	return '<img src="'.$imgsrc.'" align="right" />';
 2699:     } else {
 2700: 	return '';
 2701:     }
 2702: }
 2703: 
 2704: =pod
 2705: 
 2706: =back
 2707: 
 2708: =head1 Access .tab File Data
 2709: 
 2710: =over 4
 2711: 
 2712: =item * &languageids() 
 2713: 
 2714: returns list of all language ids
 2715: 
 2716: =cut
 2717: 
 2718: sub languageids {
 2719:     return sort(keys(%language));
 2720: }
 2721: 
 2722: =pod
 2723: 
 2724: =item * &languagedescription() 
 2725: 
 2726: returns description of a specified language id
 2727: 
 2728: =cut
 2729: 
 2730: sub languagedescription {
 2731:     my $code=shift;
 2732:     return  ($supported_language{$code}?'* ':'').
 2733:             $language{$code}.
 2734: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2735: }
 2736: 
 2737: sub plainlanguagedescription {
 2738:     my $code=shift;
 2739:     return $language{$code};
 2740: }
 2741: 
 2742: sub supportedlanguagecode {
 2743:     my $code=shift;
 2744:     return $supported_language{$code};
 2745: }
 2746: 
 2747: =pod
 2748: 
 2749: =item * &copyrightids() 
 2750: 
 2751: returns list of all copyrights
 2752: 
 2753: =cut
 2754: 
 2755: sub copyrightids {
 2756:     return sort(keys(%cprtag));
 2757: }
 2758: 
 2759: =pod
 2760: 
 2761: =item * &copyrightdescription() 
 2762: 
 2763: returns description of a specified copyright id
 2764: 
 2765: =cut
 2766: 
 2767: sub copyrightdescription {
 2768:     return &mt($cprtag{shift(@_)});
 2769: }
 2770: 
 2771: =pod
 2772: 
 2773: =item * &source_copyrightids() 
 2774: 
 2775: returns list of all source copyrights
 2776: 
 2777: =cut
 2778: 
 2779: sub source_copyrightids {
 2780:     return sort(keys(%scprtag));
 2781: }
 2782: 
 2783: =pod
 2784: 
 2785: =item * &source_copyrightdescription() 
 2786: 
 2787: returns description of a specified source copyright id
 2788: 
 2789: =cut
 2790: 
 2791: sub source_copyrightdescription {
 2792:     return &mt($scprtag{shift(@_)});
 2793: }
 2794: 
 2795: =pod
 2796: 
 2797: =item * &filecategories() 
 2798: 
 2799: returns list of all file categories
 2800: 
 2801: =cut
 2802: 
 2803: sub filecategories {
 2804:     return sort(keys(%category_extensions));
 2805: }
 2806: 
 2807: =pod
 2808: 
 2809: =item * &filecategorytypes() 
 2810: 
 2811: returns list of file types belonging to a given file
 2812: category
 2813: 
 2814: =cut
 2815: 
 2816: sub filecategorytypes {
 2817:     my ($cat) = @_;
 2818:     return @{$category_extensions{lc($cat)}};
 2819: }
 2820: 
 2821: =pod
 2822: 
 2823: =item * &fileembstyle() 
 2824: 
 2825: returns embedding style for a specified file type
 2826: 
 2827: =cut
 2828: 
 2829: sub fileembstyle {
 2830:     return $fe{lc(shift(@_))};
 2831: }
 2832: 
 2833: sub filemimetype {
 2834:     return $fm{lc(shift(@_))};
 2835: }
 2836: 
 2837: 
 2838: sub filecategoryselect {
 2839:     my ($name,$value)=@_;
 2840:     return &select_form($value,$name,
 2841: 			'' => &mt('Any category'),
 2842: 			map { $_,$_ } sort(keys(%category_extensions)));
 2843: }
 2844: 
 2845: =pod
 2846: 
 2847: =item * &filedescription() 
 2848: 
 2849: returns description for a specified file type
 2850: 
 2851: =cut
 2852: 
 2853: sub filedescription {
 2854:     my $file_description = $fd{lc(shift())};
 2855:     $file_description =~ s:([\[\]]):~$1:g;
 2856:     return &mt($file_description);
 2857: }
 2858: 
 2859: =pod
 2860: 
 2861: =item * &filedescriptionex() 
 2862: 
 2863: returns description for a specified file type with
 2864: extra formatting
 2865: 
 2866: =cut
 2867: 
 2868: sub filedescriptionex {
 2869:     my $ex=shift;
 2870:     my $file_description = $fd{lc($ex)};
 2871:     $file_description =~ s:([\[\]]):~$1:g;
 2872:     return '.'.$ex.' '.&mt($file_description);
 2873: }
 2874: 
 2875: # End of .tab access
 2876: =pod
 2877: 
 2878: =back
 2879: 
 2880: =cut
 2881: 
 2882: # ------------------------------------------------------------------ File Types
 2883: sub fileextensions {
 2884:     return sort(keys(%fe));
 2885: }
 2886: 
 2887: # ----------------------------------------------------------- Display Languages
 2888: # returns a hash with all desired display languages
 2889: #
 2890: 
 2891: sub display_languages {
 2892:     my %languages=();
 2893:     foreach my $lang (&preferred_languages()) {
 2894: 	$languages{$lang}=1;
 2895:     }
 2896:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2897:     if ($env{'form.displaylanguage'}) {
 2898: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2899: 	    $languages{$lang}=1;
 2900:         }
 2901:     }
 2902:     return %languages;
 2903: }
 2904: 
 2905: sub preferred_languages {
 2906:     my @languages=();
 2907:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2908: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2909: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2910:     }
 2911:     if ($env{'environment.languages'}) {
 2912: 	@languages=(@languages,
 2913: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
 2914:     }
 2915:     my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
 2916:     if ($browser) {
 2917: 	my @browser = 
 2918: 	    map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
 2919: 	push(@languages,@browser);
 2920:     }
 2921: 
 2922:     foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
 2923:                          $Apache::lonnet::perlvar{'lonDefDomain'}) {
 2924:         if ($domtype ne '') {
 2925:             my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
 2926:             if ($domdefs{'lang_def'} ne '') {
 2927:                 push(@languages,$domdefs{'lang_def'});
 2928:             }
 2929:         }
 2930:     }
 2931: # turn "en-ca" into "en-ca,en"
 2932:     my @genlanguages;
 2933:     foreach my $lang (@languages) {
 2934: 	unless ($lang=~/\w/) { next; }
 2935: 	push(@genlanguages,$lang);
 2936: 	if ($lang=~/(\-|\_)/) {
 2937: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2938: 	}
 2939:     }
 2940:     #uniqueify the languages list
 2941:     my %count;
 2942:     @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
 2943:     return @genlanguages;
 2944: }
 2945: 
 2946: sub languages {
 2947:     my ($possible_langs) = @_;
 2948:     my @preferred_langs = &preferred_languages();
 2949:     if (!ref($possible_langs)) {
 2950: 	if( wantarray ) {
 2951: 	    return @preferred_langs;
 2952: 	} else {
 2953: 	    return $preferred_langs[0];
 2954: 	}
 2955:     }
 2956:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 2957:     my @preferred_possibilities;
 2958:     foreach my $preferred_lang (@preferred_langs) {
 2959: 	if (exists($possibilities{$preferred_lang})) {
 2960: 	    push(@preferred_possibilities, $preferred_lang);
 2961: 	}
 2962:     }
 2963:     if( wantarray ) {
 2964: 	return @preferred_possibilities;
 2965:     }
 2966:     return $preferred_possibilities[0];
 2967: }
 2968: 
 2969: ###############################################################
 2970: ##               Student Answer Attempts                     ##
 2971: ###############################################################
 2972: 
 2973: =pod
 2974: 
 2975: =head1 Alternate Problem Views
 2976: 
 2977: =over 4
 2978: 
 2979: =item * &get_previous_attempt($symb, $username, $domain, $course,
 2980:     $getattempt, $regexp, $gradesub)
 2981: 
 2982: Return string with previous attempt on problem. Arguments:
 2983: 
 2984: =over 4
 2985: 
 2986: =item * $symb: Problem, including path
 2987: 
 2988: =item * $username: username of the desired student
 2989: 
 2990: =item * $domain: domain of the desired student
 2991: 
 2992: =item * $course: Course ID
 2993: 
 2994: =item * $getattempt: Leave blank for all attempts, otherwise put
 2995:     something
 2996: 
 2997: =item * $regexp: if string matches this regexp, the string will be
 2998:     sent to $gradesub
 2999: 
 3000: =item * $gradesub: routine that processes the string if it matches $regexp
 3001: 
 3002: =back
 3003: 
 3004: The output string is a table containing all desired attempts, if any.
 3005: 
 3006: =cut
 3007: 
 3008: sub get_previous_attempt {
 3009:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3010:   my $prevattempts='';
 3011:   no strict 'refs';
 3012:   if ($symb) {
 3013:     my (%returnhash)=
 3014:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3015:     if ($returnhash{'version'}) {
 3016:       my %lasthash=();
 3017:       my $version;
 3018:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3019:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3020: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3021:         }
 3022:       }
 3023:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3024:       $prevattempts.='<th>'.&mt('History').'</th>';
 3025:       foreach my $key (sort(keys(%lasthash))) {
 3026: 	my ($ign,@parts) = split(/\./,$key);
 3027: 	if ($#parts > 0) {
 3028: 	  my $data=$parts[-1];
 3029: 	  pop(@parts);
 3030: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3031: 	} else {
 3032: 	  if ($#parts == 0) {
 3033: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3034: 	  } else {
 3035: 	    $prevattempts.='<th>'.$ign.'</th>';
 3036: 	  }
 3037: 	}
 3038:       }
 3039:       $prevattempts.=&end_data_table_header_row();
 3040:       if ($getattempt eq '') {
 3041: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3042: 	  $prevattempts.=&start_data_table_row().
 3043: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3044: 	    foreach my $key (sort(keys(%lasthash))) {
 3045: 		my $value = &format_previous_attempt_value($key,
 3046: 							   $returnhash{$version.':'.$key});
 3047: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3048: 	    }
 3049: 	  $prevattempts.=&end_data_table_row();
 3050: 	 }
 3051:       }
 3052:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3053:       foreach my $key (sort(keys(%lasthash))) {
 3054: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3055: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3056: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3057:       }
 3058:       $prevattempts.= &end_data_table_row().&end_data_table();
 3059:     } else {
 3060:       $prevattempts=
 3061: 	  &start_data_table().&start_data_table_row().
 3062: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3063: 	  &end_data_table_row().&end_data_table();
 3064:     }
 3065:   } else {
 3066:     $prevattempts=
 3067: 	  &start_data_table().&start_data_table_row().
 3068: 	  '<td>'.&mt('No data.').'</td>'.
 3069: 	  &end_data_table_row().&end_data_table();
 3070:   }
 3071: }
 3072: 
 3073: sub format_previous_attempt_value {
 3074:     my ($key,$value) = @_;
 3075:     if ($key =~ /timestamp/) {
 3076: 	$value = &Apache::lonlocal::locallocaltime($value);
 3077:     } elsif (ref($value) eq 'ARRAY') {
 3078: 	$value = '('.join(', ', @{ $value }).')';
 3079:     } else {
 3080: 	$value = &unescape($value);
 3081:     }
 3082:     return $value;
 3083: }
 3084: 
 3085: 
 3086: sub relative_to_absolute {
 3087:     my ($url,$output)=@_;
 3088:     my $parser=HTML::TokeParser->new(\$output);
 3089:     my $token;
 3090:     my $thisdir=$url;
 3091:     my @rlinks=();
 3092:     while ($token=$parser->get_token) {
 3093: 	if ($token->[0] eq 'S') {
 3094: 	    if ($token->[1] eq 'a') {
 3095: 		if ($token->[2]->{'href'}) {
 3096: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3097: 		}
 3098: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3099: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3100: 	    } elsif ($token->[1] eq 'base') {
 3101: 		$thisdir=$token->[2]->{'href'};
 3102: 	    }
 3103: 	}
 3104:     }
 3105:     $thisdir=~s-/[^/]*$--;
 3106:     foreach my $link (@rlinks) {
 3107: 	unless (($link=~/^http:\/\//i) ||
 3108: 		($link=~/^\//) ||
 3109: 		($link=~/^javascript:/i) ||
 3110: 		($link=~/^mailto:/i) ||
 3111: 		($link=~/^\#/)) {
 3112: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3113: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3114: 	}
 3115:     }
 3116: # -------------------------------------------------- Deal with Applet codebases
 3117:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3118:     return $output;
 3119: }
 3120: 
 3121: =pod
 3122: 
 3123: =item * &get_student_view()
 3124: 
 3125: show a snapshot of what student was looking at
 3126: 
 3127: =cut
 3128: 
 3129: sub get_student_view {
 3130:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3131:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3132:   my (%form);
 3133:   my @elements=('symb','courseid','domain','username');
 3134:   foreach my $element (@elements) {
 3135:       $form{'grade_'.$element}=eval '$'.$element #'
 3136:   }
 3137:   if (defined($moreenv)) {
 3138:       %form=(%form,%{$moreenv});
 3139:   }
 3140:   if (defined($target)) { $form{'grade_target'} = $target; }
 3141:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3142:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 3143:   $userview=~s/\<body[^\>]*\>//gi;
 3144:   $userview=~s/\<\/body\>//gi;
 3145:   $userview=~s/\<html\>//gi;
 3146:   $userview=~s/\<\/html\>//gi;
 3147:   $userview=~s/\<head\>//gi;
 3148:   $userview=~s/\<\/head\>//gi;
 3149:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3150:   $userview=&relative_to_absolute($feedurl,$userview);
 3151:   return $userview;
 3152: }
 3153: 
 3154: =pod
 3155: 
 3156: =item * &get_student_answers() 
 3157: 
 3158: show a snapshot of how student was answering problem
 3159: 
 3160: =cut
 3161: 
 3162: sub get_student_answers {
 3163:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3164:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3165:   my (%moreenv);
 3166:   my @elements=('symb','courseid','domain','username');
 3167:   foreach my $element (@elements) {
 3168:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3169:   }
 3170:   $moreenv{'grade_target'}='answer';
 3171:   %moreenv=(%form,%moreenv);
 3172:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3173:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3174:   return $userview;
 3175: }
 3176: 
 3177: =pod
 3178: 
 3179: =item * &submlink()
 3180: 
 3181: Inputs: $text $uname $udom $symb $target
 3182: 
 3183: Returns: A link to grades.pm such as to see the SUBM view of a student
 3184: 
 3185: =cut
 3186: 
 3187: ###############################################
 3188: sub submlink {
 3189:     my ($text,$uname,$udom,$symb,$target)=@_;
 3190:     if (!($uname && $udom)) {
 3191: 	(my $cursymb, my $courseid,$udom,$uname)=
 3192: 	    &Apache::lonnet::whichuser($symb);
 3193: 	if (!$symb) { $symb=$cursymb; }
 3194:     }
 3195:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3196:     $symb=&escape($symb);
 3197:     if ($target) { $target="target=\"$target\""; }
 3198:     return '<a href="/adm/grades?&command=submission&'.
 3199: 	'symb='.$symb.'&student='.$uname.
 3200: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3201: }
 3202: ##############################################
 3203: 
 3204: =pod
 3205: 
 3206: =item * &pgrdlink()
 3207: 
 3208: Inputs: $text $uname $udom $symb $target
 3209: 
 3210: Returns: A link to grades.pm such as to see the PGRD view of a student
 3211: 
 3212: =cut
 3213: 
 3214: ###############################################
 3215: sub pgrdlink {
 3216:     my $link=&submlink(@_);
 3217:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3218:     return $link;
 3219: }
 3220: ##############################################
 3221: 
 3222: =pod
 3223: 
 3224: =item * &pprmlink()
 3225: 
 3226: Inputs: $text $uname $udom $symb $target
 3227: 
 3228: Returns: A link to parmset.pm such as to see the PPRM view of a
 3229: student and a specific resource
 3230: 
 3231: =cut
 3232: 
 3233: ###############################################
 3234: sub pprmlink {
 3235:     my ($text,$uname,$udom,$symb,$target)=@_;
 3236:     if (!($uname && $udom)) {
 3237: 	(my $cursymb, my $courseid,$udom,$uname)=
 3238: 	    &Apache::lonnet::whichuser($symb);
 3239: 	if (!$symb) { $symb=$cursymb; }
 3240:     }
 3241:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3242:     $symb=&escape($symb);
 3243:     if ($target) { $target="target=\"$target\""; }
 3244:     return '<a href="/adm/parmset?command=set&amp;'.
 3245: 	'symb='.$symb.'&amp;uname='.$uname.
 3246: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3247: }
 3248: ##############################################
 3249: 
 3250: =pod
 3251: 
 3252: =back
 3253: 
 3254: =cut
 3255: 
 3256: ###############################################
 3257: 
 3258: 
 3259: sub timehash {
 3260:     my @ltime=localtime(shift);
 3261:     return ( 'seconds' => $ltime[0],
 3262:              'minutes' => $ltime[1],
 3263:              'hours'   => $ltime[2],
 3264:              'day'     => $ltime[3],
 3265:              'month'   => $ltime[4]+1,
 3266:              'year'    => $ltime[5]+1900,
 3267:              'weekday' => $ltime[6],
 3268:              'dayyear' => $ltime[7]+1,
 3269:              'dlsav'   => $ltime[8] );
 3270: }
 3271: 
 3272: sub utc_string {
 3273:     my ($date)=@_;
 3274:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3275: }
 3276: 
 3277: sub maketime {
 3278:     my %th=@_;
 3279:     return POSIX::mktime(
 3280:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3281:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3282: }
 3283: 
 3284: #########################################
 3285: 
 3286: sub findallcourses {
 3287:     my ($roles,$uname,$udom) = @_;
 3288:     my %roles;
 3289:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3290:     my %courses;
 3291:     my $now=time;
 3292:     if (!defined($uname)) {
 3293:         $uname = $env{'user.name'};
 3294:     }
 3295:     if (!defined($udom)) {
 3296:         $udom = $env{'user.domain'};
 3297:     }
 3298:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3299:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3300:         if (!%roles) {
 3301:             %roles = (
 3302:                        cc => 1,
 3303:                        in => 1,
 3304:                        ep => 1,
 3305:                        ta => 1,
 3306:                        cr => 1,
 3307:                        st => 1,
 3308:              );
 3309:         }
 3310:         foreach my $entry (keys(%roleshash)) {
 3311:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3312:             if ($trole =~ /^cr/) { 
 3313:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3314:             } else {
 3315:                 next if (!exists($roles{$trole}));
 3316:             }
 3317:             if ($tend) {
 3318:                 next if ($tend < $now);
 3319:             }
 3320:             if ($tstart) {
 3321:                 next if ($tstart > $now);
 3322:             }
 3323:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3324:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3325:             if ($secpart eq '') {
 3326:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3327:                 $sec = 'none';
 3328:                 $realsec = '';
 3329:             } else {
 3330:                 $cnum = $cnumpart;
 3331:                 ($sec,$role) = split(/_/,$secpart);
 3332:                 $realsec = $sec;
 3333:             }
 3334:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3335:         }
 3336:     } else {
 3337:         foreach my $key (keys(%env)) {
 3338: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3339:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3340: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3341: 	        next if ($role eq 'ca' || $role eq 'aa');
 3342: 	        next if (%roles && !exists($roles{$role}));
 3343: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3344:                 my $active=1;
 3345:                 if ($starttime) {
 3346: 		    if ($now<$starttime) { $active=0; }
 3347:                 }
 3348:                 if ($endtime) {
 3349:                     if ($now>$endtime) { $active=0; }
 3350:                 }
 3351:                 if ($active) {
 3352:                     if ($sec eq '') {
 3353:                         $sec = 'none';
 3354:                     }
 3355:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3356:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3357:                 }
 3358:             }
 3359:         }
 3360:     }
 3361:     return %courses;
 3362: }
 3363: 
 3364: ###############################################
 3365: 
 3366: sub blockcheck {
 3367:     my ($setters,$activity,$uname,$udom) = @_;
 3368: 
 3369:     if (!defined($udom)) {
 3370:         $udom = $env{'user.domain'};
 3371:     }
 3372:     if (!defined($uname)) {
 3373:         $uname = $env{'user.name'};
 3374:     }
 3375: 
 3376:     # If uname and udom are for a course, check for blocks in the course.
 3377: 
 3378:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3379:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3380:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3381:         return ($startblock,$endblock);
 3382:     }
 3383: 
 3384:     my $startblock = 0;
 3385:     my $endblock = 0;
 3386:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3387: 
 3388:     # If uname is for a user, and activity is course-specific, i.e.,
 3389:     # boards, chat or groups, check for blocking in current course only.
 3390: 
 3391:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3392:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3393:         foreach my $key (keys(%live_courses)) {
 3394:             if ($key ne $env{'request.course.id'}) {
 3395:                 delete($live_courses{$key});
 3396:             }
 3397:         }
 3398:     }
 3399: 
 3400:     my $otheruser = 0;
 3401:     my %own_courses;
 3402:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3403:         # Resource belongs to user other than current user.
 3404:         $otheruser = 1;
 3405:         # Gather courses for current user
 3406:         %own_courses = 
 3407:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3408:     }
 3409: 
 3410:     # Gather active course roles - course coordinator, instructor, 
 3411:     # exam proctor, ta, student, or custom role.
 3412: 
 3413:     foreach my $course (keys(%live_courses)) {
 3414:         my ($cdom,$cnum);
 3415:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3416:             $cdom = $env{'course.'.$course.'.domain'};
 3417:             $cnum = $env{'course.'.$course.'.num'};
 3418:         } else {
 3419:             ($cdom,$cnum) = split(/_/,$course); 
 3420:         }
 3421:         my $no_ownblock = 0;
 3422:         my $no_userblock = 0;
 3423:         if ($otheruser && $activity ne 'com') {
 3424:             # Check if current user has 'evb' priv for this
 3425:             if (defined($own_courses{$course})) {
 3426:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3427:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3428:                     if ($sec ne 'none') {
 3429:                         $checkrole .= '/'.$sec;
 3430:                     }
 3431:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3432:                         $no_ownblock = 1;
 3433:                         last;
 3434:                     }
 3435:                 }
 3436:             }
 3437:             # if they have 'evb' priv and are currently not playing student
 3438:             next if (($no_ownblock) &&
 3439:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3440:         }
 3441:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3442:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3443:             if ($sec ne 'none') {
 3444:                 $checkrole .= '/'.$sec;
 3445:             }
 3446:             if ($otheruser) {
 3447:                 # Resource belongs to user other than current user.
 3448:                 # Assemble privs for that user, and check for 'evb' priv.
 3449:                 my ($trole,$tdom,$tnum,$tsec);
 3450:                 my $entry = $live_courses{$course}{$sec};
 3451:                 if ($entry =~ /^cr/) {
 3452:                     ($trole,$tdom,$tnum,$tsec) = 
 3453:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3454:                 } else {
 3455:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3456:                 }
 3457:                 my ($spec,$area,$trest,%allroles,%userroles);
 3458:                 $area = '/'.$tdom.'/'.$tnum;
 3459:                 $trest = $tnum;
 3460:                 if ($tsec ne '') {
 3461:                     $area .= '/'.$tsec;
 3462:                     $trest .= '/'.$tsec;
 3463:                 }
 3464:                 $spec = $trole.'.'.$area;
 3465:                 if ($trole =~ /^cr/) {
 3466:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3467:                                                       $tdom,$spec,$trest,$area);
 3468:                 } else {
 3469:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3470:                                                        $tdom,$spec,$trest,$area);
 3471:                 }
 3472:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3473:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3474:                     if ($1) {
 3475:                         $no_userblock = 1;
 3476:                         last;
 3477:                     }
 3478:                 }
 3479:             } else {
 3480:                 # Resource belongs to current user
 3481:                 # Check for 'evb' priv via lonnet::allowed().
 3482:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3483:                     $no_ownblock = 1;
 3484:                     last;
 3485:                 }
 3486:             }
 3487:         }
 3488:         # if they have the evb priv and are currently not playing student
 3489:         next if (($no_ownblock) &&
 3490:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3491:         next if ($no_userblock);
 3492: 
 3493:         # Retrieve blocking times and identity of blocker for course
 3494:         # of specified user, unless user has 'evb' privilege.
 3495:         
 3496:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3497:         if (($start != 0) && 
 3498:             (($startblock == 0) || ($startblock > $start))) {
 3499:             $startblock = $start;
 3500:         }
 3501:         if (($end != 0)  &&
 3502:             (($endblock == 0) || ($endblock < $end))) {
 3503:             $endblock = $end;
 3504:         }
 3505:     }
 3506:     return ($startblock,$endblock);
 3507: }
 3508: 
 3509: sub get_blocks {
 3510:     my ($setters,$activity,$cdom,$cnum) = @_;
 3511:     my $startblock = 0;
 3512:     my $endblock = 0;
 3513:     my $course = $cdom.'_'.$cnum;
 3514:     $setters->{$course} = {};
 3515:     $setters->{$course}{'staff'} = [];
 3516:     $setters->{$course}{'times'} = [];
 3517:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3518:     foreach my $record (keys(%records)) {
 3519:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3520:         if ($start <= time && $end >= time) {
 3521:             my ($staff_name,$staff_dom,$title,$blocks) =
 3522:                 &parse_block_record($records{$record});
 3523:             if ($blocks->{$activity} eq 'on') {
 3524:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3525:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3526:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3527:                     $startblock = $start;
 3528:                 }
 3529:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3530:                     $endblock = $end;
 3531:                 }
 3532:             }
 3533:         }
 3534:     }
 3535:     return ($startblock,$endblock);
 3536: }
 3537: 
 3538: sub parse_block_record {
 3539:     my ($record) = @_;
 3540:     my ($setuname,$setudom,$title,$blocks);
 3541:     if (ref($record) eq 'HASH') {
 3542:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3543:         $title = &unescape($record->{'event'});
 3544:         $blocks = $record->{'blocks'};
 3545:     } else {
 3546:         my @data = split(/:/,$record,3);
 3547:         if (scalar(@data) eq 2) {
 3548:             $title = $data[1];
 3549:             ($setuname,$setudom) = split(/@/,$data[0]);
 3550:         } else {
 3551:             ($setuname,$setudom,$title) = @data;
 3552:         }
 3553:         $blocks = { 'com' => 'on' };
 3554:     }
 3555:     return ($setuname,$setudom,$title,$blocks);
 3556: }
 3557: 
 3558: sub build_block_table {
 3559:     my ($startblock,$endblock,$setters) = @_;
 3560:     my %lt = &Apache::lonlocal::texthash(
 3561:         'cacb' => 'Currently active communication blocks',
 3562:         'cour' => 'Course',
 3563:         'dura' => 'Duration',
 3564:         'blse' => 'Block set by'
 3565:     );
 3566:     my $output;
 3567:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3568:     $output .= &start_data_table();
 3569:     $output .= '
 3570: <tr>
 3571:  <th>'.$lt{'cour'}.'</th>
 3572:  <th>'.$lt{'dura'}.'</th>
 3573:  <th>'.$lt{'blse'}.'</th>
 3574: </tr>
 3575: ';
 3576:     foreach my $course (keys(%{$setters})) {
 3577:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3578:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3579:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3580:             my $fullname = &plainname($uname,$udom);
 3581:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3582:                 && $env{'user.name'} ne 'public' 
 3583:                 && $env{'user.domain'} ne 'public') {
 3584:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3585:             }
 3586:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3587:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3588:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3589:             $output .= &Apache::loncommon::start_data_table_row().
 3590:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3591:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3592:                        '<td>'.$fullname.'</td>'.
 3593:                         &Apache::loncommon::end_data_table_row();
 3594:         }
 3595:     }
 3596:     $output .= &end_data_table();
 3597: }
 3598: 
 3599: sub blocking_status {
 3600:     my ($activity,$uname,$udom) = @_;
 3601:     my %setters;
 3602:     my ($blocked,$output,$ownitem,$is_course);
 3603:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3604:     if ($startblock && $endblock) {
 3605:         $blocked = 1;
 3606:         if (wantarray) {
 3607:             my $category;
 3608:             if ($activity eq 'boards') {
 3609:                 $category = 'Discussion posts in this course';
 3610:             } elsif ($activity eq 'blogs') {
 3611:                 $category = 'Blogs';
 3612:             } elsif ($activity eq 'port') {
 3613:                 if (defined($uname) && defined($udom)) {
 3614:                     if ($uname eq $env{'user.name'} &&
 3615:                         $udom eq $env{'user.domain'}) {
 3616:                         $ownitem = 1;
 3617:                     }
 3618:                 }
 3619:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3620:                 if ($ownitem) { 
 3621:                     $category = 'Your portfolio files';  
 3622:                 } elsif ($is_course) {
 3623:                     my $coursedesc;
 3624:                     foreach my $course (keys(%setters)) {
 3625:                         my %courseinfo =
 3626:                              &Apache::lonnet::coursedescription($course);
 3627:                         $coursedesc = $courseinfo{'description'};
 3628:                     }
 3629:                     $category = "Group files in the course '$coursedesc'";
 3630:                 } else {
 3631:                     $category = 'Portfolio files belonging to ';
 3632:                     if ($env{'user.name'} eq 'public' && 
 3633:                         $env{'user.domain'} eq 'public') {
 3634:                         $category .= &plainname($uname,$udom);
 3635:                     } else {
 3636:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3637:                     }
 3638:                 }
 3639:             } elsif ($activity eq 'groups') {
 3640:                 $category = 'Groups in this course';
 3641:             }
 3642:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3643:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3644:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3645:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3646:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3647:             }
 3648:         }
 3649:     }
 3650:     if (wantarray) {
 3651:         return ($blocked,$output);
 3652:     } else {
 3653:         return $blocked;
 3654:     }
 3655: }
 3656: 
 3657: ###############################################
 3658: 
 3659: =pod
 3660: 
 3661: =head1 Domain Template Functions
 3662: 
 3663: =over 4
 3664: 
 3665: =item * &determinedomain()
 3666: 
 3667: Inputs: $domain (usually will be undef)
 3668: 
 3669: Returns: Determines which domain should be used for designs
 3670: 
 3671: =cut
 3672: 
 3673: ###############################################
 3674: sub determinedomain {
 3675:     my $domain=shift;
 3676:     if (! $domain) {
 3677:         # Determine domain if we have not been given one
 3678:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3679:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3680:         if ($env{'request.role.domain'}) { 
 3681:             $domain=$env{'request.role.domain'}; 
 3682:         }
 3683:     }
 3684:     return $domain;
 3685: }
 3686: ###############################################
 3687: 
 3688: sub devalidate_domconfig_cache {
 3689:     my ($udom)=@_;
 3690:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3691: }
 3692: 
 3693: # ---------------------- Get domain configuration for a domain
 3694: sub get_domainconf {
 3695:     my ($udom) = @_;
 3696:     my $cachetime=1800;
 3697:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3698:     if (defined($cached)) { return %{$result}; }
 3699: 
 3700:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3701: 					     ['login','rolecolors'],$udom);
 3702:     my (%designhash,%legacy);
 3703:     if (keys(%domconfig) > 0) {
 3704:         if (ref($domconfig{'login'}) eq 'HASH') {
 3705:             if (keys(%{$domconfig{'login'}})) {
 3706:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3707:                     $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3708:                 }
 3709:             } else {
 3710:                 $legacy{'login'} = 1;
 3711:             }
 3712:         } else {
 3713:             $legacy{'login'} = 1;
 3714:         }
 3715:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3716:             if (keys(%{$domconfig{'rolecolors'}})) {
 3717:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3718:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3719:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3720:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3721:                         }
 3722:                     }
 3723:                 }
 3724:             } else {
 3725:                 $legacy{'rolecolors'} = 1;
 3726:             }
 3727:         } else {
 3728:             $legacy{'rolecolors'} = 1;
 3729:         }
 3730:         if (keys(%legacy) > 0) {
 3731:             my %legacyhash = &get_legacy_domconf($udom);
 3732:             foreach my $item (keys(%legacyhash)) {
 3733:                 if ($item =~ /^\Q$udom\E\.login/) {
 3734:                     if ($legacy{'login'}) { 
 3735:                         $designhash{$item} = $legacyhash{$item};
 3736:                     }
 3737:                 } else {
 3738:                     if ($legacy{'rolecolors'}) {
 3739:                         $designhash{$item} = $legacyhash{$item};
 3740:                     }
 3741:                 }
 3742:             }
 3743:         }
 3744:     } else {
 3745:         %designhash = &get_legacy_domconf($udom); 
 3746:     }
 3747:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 3748: 				  $cachetime);
 3749:     return %designhash;
 3750: }
 3751: 
 3752: sub get_legacy_domconf {
 3753:     my ($udom) = @_;
 3754:     my %legacyhash;
 3755:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 3756:     my $designfile =  $designdir.'/'.$udom.'.tab';
 3757:     if (-e $designfile) {
 3758:         if ( open (my $fh,"<$designfile") ) {
 3759:             while (my $line = <$fh>) {
 3760:                 next if ($line =~ /^\#/);
 3761:                 chomp($line);
 3762:                 my ($key,$val)=(split(/\=/,$line));
 3763:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 3764:             }
 3765:             close($fh);
 3766:         }
 3767:     }
 3768:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 3769:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 3770:     }
 3771:     return %legacyhash;
 3772: }
 3773: 
 3774: =pod
 3775: 
 3776: =item * &domainlogo()
 3777: 
 3778: Inputs: $domain (usually will be undef)
 3779: 
 3780: Returns: A link to a domain logo, if the domain logo exists.
 3781: If the domain logo does not exist, a description of the domain.
 3782: 
 3783: =cut
 3784: 
 3785: ###############################################
 3786: sub domainlogo {
 3787:     my $domain = &determinedomain(shift);
 3788:     my %designhash = &get_domainconf($domain);    
 3789:     # See if there is a logo
 3790:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 3791:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 3792:         if ($imgsrc =~ m{^/(adm|res)/}) {
 3793: 	    if ($imgsrc =~ m{^/res/}) {
 3794: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 3795: 		&Apache::lonnet::repcopy($local_name);
 3796: 	    }
 3797: 	   $imgsrc = &lonhttpdurl($imgsrc);
 3798:         } 
 3799:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 3800:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 3801:         return &Apache::lonnet::domain($domain,'description');
 3802:     } else {
 3803:         return '';
 3804:     }
 3805: }
 3806: ##############################################
 3807: 
 3808: =pod
 3809: 
 3810: =item * &designparm()
 3811: 
 3812: Inputs: $which parameter; $domain (usually will be undef)
 3813: 
 3814: Returns: value of designparamter $which
 3815: 
 3816: =cut
 3817: 
 3818: 
 3819: ##############################################
 3820: sub designparm {
 3821:     my ($which,$domain)=@_;
 3822:     if ($env{'browser.blackwhite'} eq 'on') {
 3823: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 3824: 	    return '#000000';
 3825: 	}
 3826: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 3827: 	    return '#FFFFFF';
 3828: 	}
 3829: 	if ($which=~/\.tabbg$/) {
 3830: 	    return '#CCCCCC';
 3831: 	}
 3832:     }
 3833:     if (exists($env{'environment.color.'.$which})) {
 3834: 	return $env{'environment.color.'.$which};
 3835:     }
 3836:     $domain=&determinedomain($domain);
 3837:     my %domdesign = &get_domainconf($domain);
 3838:     my $output;
 3839:     if ($domdesign{$domain.'.'.$which} ne '') {
 3840: 	$output = $domdesign{$domain.'.'.$which};
 3841:     } else {
 3842:         $output = $defaultdesign{$which};
 3843:     }
 3844:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 3845:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 3846:         if ($output =~ m{^/(adm|res)/}) {
 3847: 	    if ($output =~ m{^/res/}) {
 3848: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 3849: 		&Apache::lonnet::repcopy($local_name);
 3850: 	    }
 3851:             $output = &lonhttpdurl($output);
 3852:         }
 3853:     }
 3854:     return $output;
 3855: }
 3856: 
 3857: ###############################################
 3858: ###############################################
 3859: 
 3860: =pod
 3861: 
 3862: =back
 3863: 
 3864: =head1 HTML Helpers
 3865: 
 3866: =over 4
 3867: 
 3868: =item * &bodytag()
 3869: 
 3870: Returns a uniform header for LON-CAPA web pages.
 3871: 
 3872: Inputs: 
 3873: 
 3874: =over 4
 3875: 
 3876: =item * $title, A title to be displayed on the page.
 3877: 
 3878: =item * $function, the current role (can be undef).
 3879: 
 3880: =item * $addentries, extra parameters for the <body> tag.
 3881: 
 3882: =item * $bodyonly, if defined, only return the <body> tag.
 3883: 
 3884: =item * $domain, if defined, force a given domain.
 3885: 
 3886: =item * $forcereg, if page should register as content page (relevant for 
 3887:             text interface only)
 3888: 
 3889: =item * $customtitle, alternate text to use instead of $title
 3890:                       in the title box that appears, this text
 3891:                       is not auto translated like the $title is
 3892: 
 3893: =item * $notopbar, if true, keep the 'what is this' info but remove the
 3894:                    navigational links
 3895: 
 3896: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 3897: 
 3898: =item * $notitle, if true keep the nav controls, but remove the title bar
 3899: 
 3900: =item * $no_inline_link, if true and in remote mode, don't show the 
 3901:          'Switch To Inline Menu' link
 3902: 
 3903: =item * $args, optional argument valid values are
 3904:             no_auto_mt_title -> prevents &mt()ing the title arg
 3905:             inherit_jsmath -> when creating popup window in a page,
 3906:                               should it have jsmath forced on by the
 3907:                               current page
 3908: 
 3909: =back
 3910: 
 3911: Returns: A uniform header for LON-CAPA web pages.  
 3912: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 3913: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 3914: other decorations will be returned.
 3915: 
 3916: =cut
 3917: 
 3918: sub bodytag {
 3919:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 3920: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 3921: 
 3922:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 3923: 
 3924:     $function = &get_users_function() if (!$function);
 3925:     my $img =    &designparm($function.'.img',$domain);
 3926:     my $font =   &designparm($function.'.font',$domain);
 3927:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 3928: 
 3929:     my %design = ( 'style'   => 'margin-top: 0px',
 3930: 		   'bgcolor' => $pgbg,
 3931: 		   'text'    => $font,
 3932:                    'alink'   => &designparm($function.'.alink',$domain),
 3933: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 3934: 		   'link'    => &designparm($function.'.link',$domain),);
 3935:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 3936: 
 3937:  # role and realm
 3938:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 3939:     if ($role  eq 'ca') {
 3940:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 3941:         $realm = &plainname($rname,$rdom);
 3942:     } 
 3943: # realm
 3944:     if ($env{'request.course.id'}) {
 3945:         if ($env{'request.role'} !~ /^cr/) {
 3946:             $role = &Apache::lonnet::plaintext($role,&course_type());
 3947:         }
 3948: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 3949:     } else {
 3950:         $role = &Apache::lonnet::plaintext($role);
 3951:     }
 3952: 
 3953:     if (!$realm) { $realm='&nbsp;'; }
 3954: # Set messages
 3955:     my $messages=&domainlogo($domain);
 3956: 
 3957:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 3958: 
 3959: # construct main body tag
 3960:     my $bodytag = "<body $extra_body_attr>".
 3961: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 3962: 
 3963:     if ($bodyonly) {
 3964:         return $bodytag;
 3965:     } elsif ($env{'browser.interface'} eq 'textual') {
 3966: # Accessibility
 3967:           
 3968: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 3969: 	if (!$notitle) {
 3970: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 3971: 	}
 3972: 	return $bodytag;
 3973:     }
 3974: 
 3975:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 3976:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3977: 	undef($role);
 3978:     } else {
 3979: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 3980:     }
 3981:     
 3982:     my $roleinfo=(<<ENDROLE);
 3983: <td class="LC_title_bar_who">
 3984: <div class="LC_title_bar_name">
 3985:     $name
 3986:     &nbsp;
 3987: </div>
 3988: <div class="LC_title_bar_role">
 3989: $role&nbsp;
 3990: </div>
 3991: <div class="LC_title_bar_realm">
 3992: $realm&nbsp;
 3993: </div>
 3994: </td>
 3995: ENDROLE
 3996: 
 3997:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 3998:     if ($customtitle) {
 3999:         $titleinfo = $customtitle;
 4000:     }
 4001:     #
 4002:     # Extra info if you are the DC
 4003:     my $dc_info = '';
 4004:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4005:                         $env{'course.'.$env{'request.course.id'}.
 4006:                                  '.domain'}.'/'})) {
 4007:         my $cid = $env{'request.course.id'};
 4008:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4009:         $dc_info =~ s/\s+$//;
 4010:         $dc_info = '('.$dc_info.')';
 4011:     }
 4012: 
 4013:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4014:         # No Remote
 4015: 	if ($env{'request.state'} eq 'construct') {
 4016: 	    $forcereg=1;
 4017: 	}
 4018: 
 4019: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4020: 	    # this is for resources; directories have customtitle, and crumbs
 4021:             # and select recent are created in lonpubdir.pm  
 4022: 	    my ($uname,$thisdisfn)=
 4023: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4024: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4025: 	    $formaction=~s/\/+/\//g;
 4026: 
 4027: 	    my $parentpath = '';
 4028: 	    my $lastitem = '';
 4029: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4030: 		$parentpath = $1;
 4031: 		$lastitem = $2;
 4032: 	    } else {
 4033: 		$lastitem = $thisdisfn;
 4034: 	    }
 4035: 	    $titleinfo = 
 4036: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4037: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4038: 		.'<form name="dirs" method="post" action="'.$formaction
 4039: 		.'" target="_top"><tt><b>'
 4040: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4041: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4042: 		.'</form>'
 4043: 		.&Apache::lonmenu::constspaceform();
 4044:         }
 4045: 
 4046:         my $titletable;
 4047: 	if (!$notitle) {
 4048: 	    $titletable =
 4049: 		'<table id="LC_title_bar">'.
 4050:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4051: 			 '</tr></table>';
 4052: 	}
 4053: 	if ($notopbar) {
 4054: 	    $bodytag .= $titletable;
 4055: 	} else {
 4056: 	    if ($env{'request.state'} eq 'construct') {
 4057:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4058: 							  $titletable);
 4059:             } else {
 4060:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4061: 		    $titletable;
 4062:             }
 4063:         }
 4064:         return $bodytag;
 4065:     }
 4066: 
 4067: #
 4068: # Top frame rendering, Remote is up
 4069: #
 4070: 
 4071:     my $imgsrc = $img;
 4072:     if ($img =~ /^\/adm/) {
 4073:         $imgsrc = &lonhttpdurl($img);
 4074:     }
 4075:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4076: 
 4077:     # Explicit link to get inline menu
 4078:     my $menu= ($no_inline_link?''
 4079: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4080:     #
 4081:     if ($notitle) {
 4082: 	return $bodytag;
 4083:     }
 4084:     return(<<ENDBODY);
 4085: $bodytag
 4086: <table id="LC_title_bar" class="LC_with_remote">
 4087: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4088:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4089: </tr>
 4090: <tr><td>$titleinfo $dc_info $menu</td>
 4091: $roleinfo
 4092: </tr>
 4093: </table>
 4094: ENDBODY
 4095: }
 4096: 
 4097: sub make_attr_string {
 4098:     my ($register,$attr_ref) = @_;
 4099: 
 4100:     if ($attr_ref && !ref($attr_ref)) {
 4101: 	die("addentries Must be a hash ref ".
 4102: 	    join(':',caller(1))." ".
 4103: 	    join(':',caller(0))." ");
 4104:     }
 4105: 
 4106:     if ($register) {
 4107: 	my ($on_load,$on_unload);
 4108: 	foreach my $key (keys(%{$attr_ref})) {
 4109: 	    if      (lc($key) eq 'onload') {
 4110: 		$on_load.=$attr_ref->{$key}.';';
 4111: 		delete($attr_ref->{$key});
 4112: 
 4113: 	    } elsif (lc($key) eq 'onunload') {
 4114: 		$on_unload.=$attr_ref->{$key}.';';
 4115: 		delete($attr_ref->{$key});
 4116: 	    }
 4117: 	}
 4118: 	$attr_ref->{'onload'}  =
 4119: 	    &Apache::lonmenu::loadevents().  $on_load;
 4120: 	$attr_ref->{'onunload'}=
 4121: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4122:     }
 4123: 
 4124: # Accessibility font enhance
 4125:     if ($env{'browser.fontenhance'} eq 'on') {
 4126: 	my $style;
 4127: 	foreach my $key (keys(%{$attr_ref})) {
 4128: 	    if (lc($key) eq 'style') {
 4129: 		$style.=$attr_ref->{$key}.';';
 4130: 		delete($attr_ref->{$key});
 4131: 	    }
 4132: 	}
 4133: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4134:     }
 4135: 
 4136:     if ($env{'browser.blackwhite'} eq 'on') {
 4137: 	delete($attr_ref->{'font'});
 4138: 	delete($attr_ref->{'link'});
 4139: 	delete($attr_ref->{'alink'});
 4140: 	delete($attr_ref->{'vlink'});
 4141: 	delete($attr_ref->{'bgcolor'});
 4142: 	delete($attr_ref->{'background'});
 4143:     }
 4144: 
 4145:     my $attr_string;
 4146:     foreach my $attr (keys(%$attr_ref)) {
 4147: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4148:     }
 4149:     return $attr_string;
 4150: }
 4151: 
 4152: 
 4153: ###############################################
 4154: ###############################################
 4155: 
 4156: =pod
 4157: 
 4158: =item * &endbodytag()
 4159: 
 4160: Returns a uniform footer for LON-CAPA web pages.
 4161: 
 4162: Inputs: 1 - optional reference to an args hash
 4163: If in the hash, key for noredirectlink has a value which evaluates to true,
 4164: a 'Continue' link is not displayed if the page contains an
 4165: internal redirect in the <head></head> section,
 4166: i.e., $env{'internal.head.redirect'} exists   
 4167: 
 4168: =cut
 4169: 
 4170: sub endbodytag {
 4171:     my ($args) = @_;
 4172:     my $endbodytag='</body>';
 4173:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4174:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4175:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4176: 	    $endbodytag=
 4177: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4178: 	        &mt('Continue').'</a>'.
 4179: 	        $endbodytag;
 4180:         }
 4181:     }
 4182:     return $endbodytag;
 4183: }
 4184: 
 4185: =pod
 4186: 
 4187: =item * &standard_css()
 4188: 
 4189: Returns a style sheet
 4190: 
 4191: Inputs: (all optional)
 4192:             domain         -> force to color decorate a page for a specific
 4193:                                domain
 4194:             function       -> force usage of a specific rolish color scheme
 4195:             bgcolor        -> override the default page bgcolor
 4196: 
 4197: =cut
 4198: 
 4199: sub standard_css {
 4200:     my ($function,$domain,$bgcolor) = @_;
 4201:     $function  = &get_users_function() if (!$function);
 4202:     my $img    = &designparm($function.'.img',   $domain);
 4203:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4204:     my $font   = &designparm($function.'.font',  $domain);
 4205:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4206:     my $pgbg_or_bgcolor =
 4207: 	         $bgcolor ||
 4208: 	         &designparm($function.'.pgbg',  $domain);
 4209:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4210:     my $alink  = &designparm($function.'.alink', $domain);
 4211:     my $vlink  = &designparm($function.'.vlink', $domain);
 4212:     my $link   = &designparm($function.'.link',  $domain);
 4213: 
 4214:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4215:     my $mono                 = 'monospace';
 4216:     my $data_table_head      = $tabbg;
 4217:     my $data_table_light     = '#EEEEEE';
 4218:     my $data_table_dark      = '#DDDDDD';
 4219:     my $data_table_darker    = '#CCCCCC';
 4220:     my $data_table_highlight = '#FFFF00';
 4221:     my $mail_new             = '#FFBB77';
 4222:     my $mail_new_hover       = '#DD9955';
 4223:     my $mail_read            = '#BBBB77';
 4224:     my $mail_read_hover      = '#999944';
 4225:     my $mail_replied         = '#AAAA88';
 4226:     my $mail_replied_hover   = '#888855';
 4227:     my $mail_other           = '#99BBBB';
 4228:     my $mail_other_hover     = '#669999';
 4229:     my $table_header         = '#DDDDDD';
 4230:     my $feedback_link_bg     = '#BBBBBB';
 4231: 
 4232:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4233: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4234: 	                                                 : '0px 3px 0px 4px';
 4235: 
 4236: 
 4237:     return <<END;
 4238: h1, h2, h3, th { font-family: $sans }
 4239: a:focus { color: red; background: yellow } 
 4240: table.thinborder,
 4241: 
 4242: table.thinborder tr th {
 4243:   border-style: solid;
 4244:   border-width: 1px;
 4245:   background: $tabbg;
 4246: }
 4247: table.thinborder tr td {
 4248:   border-style: solid;
 4249:   border-width: 1px
 4250: }
 4251: 
 4252: form, .inline { display: inline; }
 4253: .center { text-align: center; }
 4254: .LC_filename {font-family: $mono; white-space:pre;}
 4255: .LC_error {
 4256:   color: red;
 4257:   font-size: larger;
 4258: }
 4259: .LC_warning,
 4260: .LC_diff_removed {
 4261:   color: red;
 4262: }
 4263: 
 4264: .LC_info,
 4265: .LC_success,
 4266: .LC_diff_added {
 4267:   color: green;
 4268: }
 4269: .LC_unknown {
 4270:   color: yellow;
 4271: }
 4272: 
 4273: .LC_icon {
 4274:   border: 0px;
 4275: }
 4276: .LC_indexer_icon {
 4277:   border: 0px;
 4278:   height: 22px;
 4279: }
 4280: .LC_docs_spacer {
 4281:   width: 25px;
 4282:   height: 1px;
 4283:   border: 0px;
 4284: }
 4285: 
 4286: .LC_internal_info {
 4287:   color: #999;
 4288: }
 4289: 
 4290: table.LC_pastsubmission {
 4291:   border: 1px solid black;
 4292:   margin: 2px;
 4293: }
 4294: 
 4295: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4296:   width: 100%;
 4297:   background: $pgbg;
 4298:   border: 2px;
 4299:   border-collapse: separate;
 4300:   padding: 0px;
 4301: }
 4302: 
 4303: table#LC_title_bar, table.LC_breadcrumbs, 
 4304: table#LC_title_bar.LC_with_remote {
 4305:   width: 100%;
 4306:   border-color: $pgbg;
 4307:   border-style: solid;
 4308:   border-width: $border;
 4309: 
 4310:   background: $pgbg;
 4311:   font-family: $sans;
 4312:   border-collapse: collapse;
 4313:   padding: 0px;
 4314: }
 4315: 
 4316: table.LC_docs_path {
 4317:   width: 100%;
 4318:   border: 0;
 4319:   background: $pgbg;
 4320:   font-family: $sans;
 4321:   border-collapse: collapse;
 4322:   padding: 0px;
 4323: }
 4324: 
 4325: table#LC_title_bar td {
 4326:   background: $tabbg;
 4327: }
 4328: table#LC_title_bar td.LC_title_bar_who {
 4329:   background: $tabbg;
 4330:   color: $font;
 4331:   font: small $sans;
 4332:   text-align: right;
 4333: }
 4334: span.LC_metadata {
 4335:     font-family: $sans;
 4336: }
 4337: span.LC_title_bar_title {
 4338:   font: bold x-large $sans;
 4339: }
 4340: table#LC_title_bar td.LC_title_bar_domain_logo {
 4341:   background: $sidebg;
 4342:   text-align: right;
 4343:   padding: 0px;
 4344: }
 4345: table#LC_title_bar td.LC_title_bar_role_logo {
 4346:   background: $sidebg;
 4347:   padding: 0px;
 4348: }
 4349: 
 4350: table#LC_menubuttons_mainmenu {
 4351:   width: 100%;
 4352:   border: 0px;
 4353:   border-spacing: 1px;
 4354:   padding: 0px 1px;
 4355:   margin: 0px;
 4356:   border-collapse: separate;
 4357: }
 4358: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4359:   border: 0px;
 4360: }
 4361: table#LC_top_nav td {
 4362:   background: $tabbg;
 4363:   border: 0px;
 4364:   font-size: small;
 4365: }
 4366: table#LC_top_nav td a, div#LC_top_nav a {
 4367:   color: $font;
 4368:   font-family: $sans;
 4369: }
 4370: table#LC_top_nav td.LC_top_nav_logo {
 4371:   background: $tabbg;
 4372:   text-align: left;
 4373:   white-space: nowrap;
 4374:   width: 31px;
 4375: }
 4376: table#LC_top_nav td.LC_top_nav_logo img {
 4377:   border: 0px;
 4378:   vertical-align: bottom;
 4379: }
 4380: table#LC_top_nav td.LC_top_nav_exit,
 4381: table#LC_top_nav td.LC_top_nav_help {
 4382:   width: 2.0em;
 4383: }
 4384: table#LC_top_nav td.LC_top_nav_login {
 4385:   width: 4.0em;
 4386:   text-align: center;
 4387: }
 4388: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4389:   background: $tabbg;
 4390:   color: $font;
 4391:   font-family: $sans;
 4392:   font-size: smaller;
 4393: }
 4394: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4395: table.LC_docs_path td.LC_docs_path_component {
 4396:   background: $tabbg;
 4397:   color: $font;
 4398:   font-family: $sans;
 4399:   font-size: larger;
 4400:   text-align: right;
 4401: }
 4402: td.LC_table_cell_checkbox {
 4403:   text-align: center;
 4404: }
 4405: 
 4406: table#LC_mainmenu td.LC_mainmenu_column {
 4407:     vertical-align: top;
 4408: }
 4409: 
 4410: .LC_menubuttons_inline_text {
 4411:   color: $font;
 4412:   font-family: $sans;
 4413:   font-size: smaller;
 4414: }
 4415: 
 4416: .LC_menubuttons_link {
 4417:   text-decoration: none;
 4418: }
 4419: 
 4420: .LC_menubuttons_category {
 4421:   color: $font;
 4422:   background: $pgbg;
 4423:   font-family: $sans;
 4424:   font-size: larger;
 4425:   font-weight: bold;
 4426: }
 4427: 
 4428: td.LC_menubuttons_text {
 4429:   width: 90%;
 4430:   color: $font;
 4431:   font-family: $sans;
 4432: }
 4433: 
 4434: td.LC_menubuttons_img {
 4435: }
 4436: 
 4437: .LC_current_location {
 4438:   font-family: $sans;
 4439:   background: $tabbg;
 4440: }
 4441: .LC_new_mail {
 4442:   font-family: $sans;
 4443:   background: $tabbg;
 4444:   font-weight: bold;
 4445: }
 4446: 
 4447: .LC_rolesmenu_is {
 4448:   font-family: $sans;
 4449: }
 4450: 
 4451: .LC_rolesmenu_selected {
 4452:   font-family: $sans;
 4453: }
 4454: 
 4455: .LC_rolesmenu_future {
 4456:   font-family: $sans;
 4457: }
 4458: 
 4459: 
 4460: .LC_rolesmenu_will {
 4461:   font-family: $sans;
 4462: }
 4463: 
 4464: .LC_rolesmenu_will_not {
 4465:   font-family: $sans;
 4466: }
 4467: 
 4468: .LC_rolesmenu_expired {
 4469:   font-family: $sans;
 4470: }
 4471: 
 4472: .LC_rolesinfo {
 4473:   font-family: $sans;
 4474: }
 4475: 
 4476: .LC_dropadd_labeltext {
 4477:   font-family: $sans;
 4478:   text-align: right;
 4479: }
 4480: 
 4481: .LC_preferences_labeltext {
 4482:   font-family: $sans;
 4483:   text-align: right;
 4484: }
 4485: 
 4486: table.LC_aboutme_port {
 4487:   border: 0px;
 4488:   border-collapse: collapse;
 4489:   border-spacing: 0px;
 4490: }
 4491: table.LC_data_table, table.LC_mail_list {
 4492:   border: 1px solid #000000;
 4493:   border-collapse: separate;
 4494:   border-spacing: 1px;
 4495:   background: $pgbg;
 4496: }
 4497: .LC_data_table_dense {
 4498:   font-size: small;
 4499: }
 4500: table.LC_nested_outer {
 4501:   border: 1px solid #000000;
 4502:   border-collapse: collapse;
 4503:   border-spacing: 0px;
 4504:   width: 100%;
 4505: }
 4506: table.LC_nested {
 4507:   border: 0px;
 4508:   border-collapse: collapse;
 4509:   border-spacing: 0px;
 4510:   width: 100%;
 4511: }
 4512: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4513: table.LC_prior_tries tr th {
 4514:   font-weight: bold;
 4515:   background-color: $data_table_head;
 4516:   font-size: smaller;
 4517: }
 4518: table.LC_data_table tr.LC_odd_row > td, 
 4519: table.LC_aboutme_port tr td {
 4520:   background-color: $data_table_light;
 4521:   padding: 2px;
 4522: }
 4523: table.LC_data_table tr.LC_even_row > td,
 4524: table.LC_aboutme_port tr.LC_even_row td {
 4525:   background-color: $data_table_dark;
 4526: }
 4527: table.LC_data_table tr.LC_data_table_highlight td {
 4528:   background-color: $data_table_darker;
 4529: }
 4530: table.LC_data_table tr td.LC_leftcol_header {
 4531:   background-color: $data_table_head;
 4532:   font-weight: bold;
 4533: }
 4534: table.LC_data_table tr.LC_empty_row td,
 4535: table.LC_nested tr.LC_empty_row td {
 4536:   background-color: #FFFFFF;
 4537:   font-weight: bold;
 4538:   font-style: italic;
 4539:   text-align: center;
 4540:   padding: 8px;
 4541: }
 4542: table.LC_nested tr.LC_empty_row td {
 4543:   padding: 4ex
 4544: }
 4545: table.LC_nested_outer tr th {
 4546:   font-weight: bold;
 4547:   background-color: $data_table_head;
 4548:   font-size: smaller;
 4549:   border-bottom: 1px solid #000000;
 4550: }
 4551: table.LC_nested_outer tr td.LC_subheader {
 4552:   background-color: $data_table_head;
 4553:   font-weight: bold;
 4554:   font-size: small;
 4555:   border-bottom: 1px solid #000000;
 4556:   text-align: right;
 4557: }
 4558: table.LC_nested tr.LC_info_row td {
 4559:   background-color: #CCC;
 4560:   font-weight: bold;
 4561:   font-size: small;
 4562:   text-align: center;
 4563: }
 4564: table.LC_nested tr.LC_info_row td.LC_left_item,
 4565: table.LC_nested_outer tr th.LC_left_item {
 4566:   text-align: left;
 4567: }
 4568: table.LC_nested td {
 4569:   background-color: #FFF;
 4570:   font-size: small;
 4571: }
 4572: table.LC_nested_outer tr th.LC_right_item,
 4573: table.LC_nested tr.LC_info_row td.LC_right_item,
 4574: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4575: table.LC_nested tr td.LC_right_item {
 4576:   text-align: right;
 4577: }
 4578: 
 4579: table.LC_nested tr.LC_odd_row td {
 4580:   background-color: #EEE;
 4581: }
 4582: 
 4583: table.LC_createuser {
 4584: }
 4585: 
 4586: table.LC_createuser tr.LC_section_row td {
 4587:   font-size: smaller;
 4588: }
 4589: 
 4590: table.LC_createuser tr.LC_info_row td  {
 4591:   background-color: #CCC;
 4592:   font-weight: bold;
 4593:   text-align: center;
 4594: }
 4595: 
 4596: table.LC_calendar {
 4597:   border: 1px solid #000000;
 4598:   border-collapse: collapse;
 4599: }
 4600: table.LC_calendar_pickdate {
 4601:   font-size: xx-small;
 4602: }
 4603: table.LC_calendar tr td {
 4604:   border: 1px solid #000000;
 4605:   vertical-align: top;
 4606: }
 4607: table.LC_calendar tr td.LC_calendar_day_empty {
 4608:   background-color: $data_table_dark;
 4609: }
 4610: table.LC_calendar tr td.LC_calendar_day_current {
 4611:   background-color: $data_table_highlight;
 4612: }
 4613: 
 4614: table.LC_mail_list tr.LC_mail_new {
 4615:   background-color: $mail_new;
 4616: }
 4617: table.LC_mail_list tr.LC_mail_new:hover {
 4618:   background-color: $mail_new_hover;
 4619: }
 4620: table.LC_mail_list tr.LC_mail_read {
 4621:   background-color: $mail_read;
 4622: }
 4623: table.LC_mail_list tr.LC_mail_read:hover {
 4624:   background-color: $mail_read_hover;
 4625: }
 4626: table.LC_mail_list tr.LC_mail_replied {
 4627:   background-color: $mail_replied;
 4628: }
 4629: table.LC_mail_list tr.LC_mail_replied:hover {
 4630:   background-color: $mail_replied_hover;
 4631: }
 4632: table.LC_mail_list tr.LC_mail_other {
 4633:   background-color: $mail_other;
 4634: }
 4635: table.LC_mail_list tr.LC_mail_other:hover {
 4636:   background-color: $mail_other_hover;
 4637: }
 4638: table.LC_mail_list tr.LC_mail_even {
 4639: }
 4640: table.LC_mail_list tr.LC_mail_odd {
 4641: }
 4642: 
 4643: 
 4644: table#LC_portfolio_actions {
 4645:   width: auto;
 4646:   background: $pgbg;
 4647:   border: 0px;
 4648:   border-spacing: 2px 2px;
 4649:   padding: 0px;
 4650:   margin: 0px;
 4651:   border-collapse: separate;
 4652: }
 4653: table#LC_portfolio_actions td.LC_label {
 4654:   background: $tabbg;
 4655:   text-align: right;
 4656: }
 4657: table#LC_portfolio_actions td.LC_value {
 4658:   background: $tabbg;
 4659: }
 4660: 
 4661: table#LC_cstr_controls {
 4662:   width: 100%;
 4663:   border-collapse: collapse;
 4664: }
 4665: table#LC_cstr_controls tr td {
 4666:   border: 4px solid $pgbg;
 4667:   padding: 4px;
 4668:   text-align: center;
 4669:   background: $tabbg;
 4670: }
 4671: table#LC_cstr_controls tr th {
 4672:   border: 4px solid $pgbg;
 4673:   background: $table_header;
 4674:   text-align: center;
 4675:   font-family: $sans;
 4676:   font-size: smaller;
 4677: }
 4678: 
 4679: table#LC_browser {
 4680:  
 4681: }
 4682: table#LC_browser tr th {
 4683:   background: $table_header;
 4684: }
 4685: table#LC_browser tr td {
 4686:   padding: 2px;
 4687: }
 4688: table#LC_browser tr.LC_browser_file,
 4689: table#LC_browser tr.LC_browser_file_published {
 4690:   background: #CCFF88;
 4691: }
 4692: table#LC_browser tr.LC_browser_file_locked,
 4693: table#LC_browser tr.LC_browser_file_unpublished {
 4694:   background: #FFAA99;
 4695: }
 4696: table#LC_browser tr.LC_browser_file_obsolete {
 4697:   background: #AAAAAA;
 4698: }
 4699: table#LC_browser tr.LC_browser_file_modified,
 4700: table#LC_browser tr.LC_browser_file_metamodified {
 4701:   background: #FFFF77;
 4702: }
 4703: table#LC_browser tr.LC_browser_folder {
 4704:   background: #CCCCFF;
 4705: }
 4706: span.LC_current_location {
 4707:   font-size: x-large;
 4708:   background: $pgbg;
 4709: }
 4710: 
 4711: span.LC_parm_menu_item {
 4712:   font-size: larger;
 4713:   font-family: $sans;
 4714: }
 4715: span.LC_parm_scope_all {
 4716:   color: red;
 4717: }
 4718: span.LC_parm_scope_folder {
 4719:   color: green;
 4720: }
 4721: span.LC_parm_scope_resource {
 4722:   color: orange;
 4723: }
 4724: span.LC_parm_part {
 4725:   color: blue;
 4726: }
 4727: span.LC_parm_folder, span.LC_parm_symb {
 4728:   font-size: x-small;
 4729:   font-family: $mono;
 4730:   color: #AAAAAA;
 4731: }
 4732: 
 4733: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4734: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4735:   border: 1px solid black;
 4736:   border-collapse: collapse;
 4737: }
 4738: table.LC_parm_overview_restrictions td {
 4739:   border-width: 1px 4px 1px 4px;
 4740:   border-style: solid;
 4741:   border-color: $pgbg;
 4742:   text-align: center;
 4743: }
 4744: table.LC_parm_overview_restrictions th {
 4745:   background: $tabbg;
 4746:   border-width: 1px 4px 1px 4px;
 4747:   border-style: solid;
 4748:   border-color: $pgbg;
 4749: }
 4750: table#LC_helpmenu {
 4751:   border: 0px;
 4752:   height: 55px;
 4753:   border-spacing: 0px;
 4754: }
 4755: 
 4756: table#LC_helpmenu fieldset legend {
 4757:   font-size: larger;
 4758:   font-weight: bold;
 4759: }
 4760: table#LC_helpmenu_links {
 4761:   width: 100%;
 4762:   border: 1px solid black;
 4763:   background: $pgbg;
 4764:   padding: 0px;
 4765:   border-spacing: 1px;
 4766: }
 4767: table#LC_helpmenu_links tr td {
 4768:   padding: 1px;
 4769:   background: $tabbg;
 4770:   text-align: center;
 4771:   font-weight: bold;
 4772: }
 4773: 
 4774: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 4775: table#LC_helpmenu_links a:active {
 4776:   text-decoration: none;
 4777:   color: $font;
 4778: }
 4779: table#LC_helpmenu_links a:hover {
 4780:   text-decoration: underline;
 4781:   color: $vlink;
 4782: }
 4783: 
 4784: .LC_chrt_popup_exists {
 4785:   border: 1px solid #339933;
 4786:   margin: -1px;
 4787: }
 4788: .LC_chrt_popup_up {
 4789:   border: 1px solid yellow;
 4790:   margin: -1px;
 4791: }
 4792: .LC_chrt_popup {
 4793:   border: 1px solid #8888FF;
 4794:   background: #CCCCFF;
 4795: }
 4796: table.LC_pick_box {
 4797:   border-collapse: separate;
 4798:   background: white;
 4799:   border: 1px solid black;
 4800:   border-spacing: 1px;
 4801: }
 4802: table.LC_pick_box td.LC_pick_box_title {
 4803:   background: $tabbg;
 4804:   font-weight: bold;
 4805:   text-align: right;
 4806:   width: 184px;
 4807:   padding: 8px;
 4808: }
 4809: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 4810:   background: $tabbg;
 4811:   font-weight: bold;
 4812:   text-align: right;
 4813:   width: 350px;
 4814:   padding: 8px;
 4815: }
 4816: 
 4817: table.LC_pick_box td.LC_pick_box_value {
 4818:   text-align: left;
 4819:   padding: 8px;
 4820: }
 4821: table.LC_pick_box td.LC_pick_box_select {
 4822:   text-align: left;
 4823:   padding: 8px;
 4824: }
 4825: table.LC_pick_box td.LC_pick_box_separator {
 4826:   padding: 0px;
 4827:   height: 1px;
 4828:   background: black;
 4829: }
 4830: table.LC_pick_box td.LC_pick_box_submit {
 4831:   text-align: right;
 4832: }
 4833: table.LC_pick_box td.LC_evenrow_value {
 4834:   text-align: left;
 4835:   padding: 8px;
 4836:   background-color: $data_table_light;
 4837: }
 4838: table.LC_pick_box td.LC_oddrow_value {
 4839:   text-align: left;
 4840:   padding: 8px;
 4841:   background-color: $data_table_light;
 4842: }
 4843: table.LC_helpform_receipt {
 4844:   width: 620px;
 4845:   border-collapse: separate;
 4846:   background: white;
 4847:   border: 1px solid black;
 4848:   border-spacing: 1px;
 4849: }
 4850: table.LC_helpform_receipt td.LC_pick_box_title {
 4851:   background: $tabbg;
 4852:   font-weight: bold;
 4853:   text-align: right;
 4854:   width: 184px;
 4855:   padding: 8px;
 4856: }
 4857: table.LC_helpform_receipt td.LC_evenrow_value {
 4858:   text-align: left;
 4859:   padding: 8px;
 4860:   background-color: $data_table_light;
 4861: }
 4862: table.LC_helpform_receipt td.LC_oddrow_value {
 4863:   text-align: left;
 4864:   padding: 8px;
 4865:   background-color: $data_table_light;
 4866: }
 4867: table.LC_helpform_receipt td.LC_pick_box_separator {
 4868:   padding: 0px;
 4869:   height: 1px;
 4870:   background: black;
 4871: }
 4872: span.LC_helpform_receipt_cat {
 4873:   font-weight: bold;
 4874: }
 4875: table.LC_group_priv_box {
 4876:   background: white;
 4877:   border: 1px solid black;
 4878:   border-spacing: 1px;
 4879: }
 4880: table.LC_group_priv_box td.LC_pick_box_title {
 4881:   background: $tabbg;
 4882:   font-weight: bold;
 4883:   text-align: right;
 4884:   width: 184px;
 4885: }
 4886: table.LC_group_priv_box td.LC_groups_fixed {
 4887:   background: $data_table_light;
 4888:   text-align: center;
 4889: }
 4890: table.LC_group_priv_box td.LC_groups_optional {
 4891:   background: $data_table_dark;
 4892:   text-align: center;
 4893: }
 4894: table.LC_group_priv_box td.LC_groups_functionality {
 4895:   background: $data_table_darker;
 4896:   text-align: center;
 4897:   font-weight: bold;
 4898: }
 4899: table.LC_group_priv td {
 4900:   text-align: left;
 4901:   padding: 0px;
 4902: }
 4903: 
 4904: table.LC_notify_front_page {
 4905:   background: white;
 4906:   border: 1px solid black;
 4907:   padding: 8px;
 4908: }
 4909: table.LC_notify_front_page td {
 4910:   padding: 8px;
 4911: }
 4912: .LC_navbuttons {
 4913:   margin: 2ex 0ex 2ex 0ex;
 4914: }
 4915: .LC_topic_bar {
 4916:   font-family: $sans;
 4917:   font-weight: bold;
 4918:   width: 100%;
 4919:   background: $tabbg;
 4920:   vertical-align: middle;
 4921:   margin: 2ex 0ex 2ex 0ex;
 4922: }
 4923: .LC_topic_bar span {
 4924:   vertical-align: middle;
 4925: }
 4926: .LC_topic_bar img {
 4927:   vertical-align: bottom;
 4928: }
 4929: table.LC_course_group_status {
 4930:   margin: 20px;
 4931: }
 4932: table.LC_status_selector td {
 4933:   vertical-align: top;
 4934:   text-align: center;
 4935:   padding: 4px;
 4936: }
 4937: table.LC_descriptive_input td.LC_description {
 4938:   vertical-align: top;
 4939:   text-align: right;
 4940:   font-weight: bold;
 4941: }
 4942: div.LC_feedback_link {
 4943:   clear: both;
 4944:   background: white;
 4945:   width: 100%;  
 4946: }
 4947: span.LC_feedback_link {
 4948:   background: $feedback_link_bg;
 4949:   font-size: larger;
 4950: }
 4951: span.LC_message_link {
 4952:   background: $feedback_link_bg;
 4953:   font-size: larger;
 4954:   position: absolute;
 4955:   right: 1em;
 4956: }
 4957: 
 4958: table.LC_prior_tries {
 4959:   border: 1px solid #000000;
 4960:   border-collapse: separate;
 4961:   border-spacing: 1px;
 4962: }
 4963: 
 4964: table.LC_prior_tries td {
 4965:   padding: 2px;
 4966: }
 4967: 
 4968: .LC_answer_correct {
 4969:   background: #AAFFAA;
 4970:   color: black;
 4971: }
 4972: .LC_answer_charged_try {
 4973:   background: #FFAAAA ! important;
 4974:   color: black;
 4975: }
 4976: .LC_answer_not_charged_try, 
 4977: .LC_answer_no_grade,
 4978: .LC_answer_late {
 4979:   background: #FFFFAA;
 4980:   color: black;
 4981: }
 4982: .LC_answer_previous {
 4983:   background: #AAAAFF;
 4984:   color: black;
 4985: }
 4986: .LC_answer_no_message {
 4987:   background: #FFFFFF;
 4988:   color: black;
 4989: }
 4990: .LC_answer_unknown {
 4991:   background: orange;
 4992:   color: black;
 4993: }
 4994: 
 4995: 
 4996: span.LC_prior_numerical,
 4997: span.LC_prior_string,
 4998: span.LC_prior_custom,
 4999: span.LC_prior_reaction,
 5000: span.LC_prior_math {
 5001:   font-family: monospace;
 5002:   white-space: pre;
 5003: }
 5004: 
 5005: span.LC_prior_string {
 5006:   font-family: monospace;
 5007:   white-space: pre;
 5008: }
 5009: 
 5010: table.LC_prior_option {
 5011:   width: 100%;
 5012:   border-collapse: collapse;
 5013: }
 5014: table.LC_prior_rank, table.LC_prior_match {
 5015:   border-collapse: collapse;
 5016: }
 5017: table.LC_prior_option tr td,
 5018: table.LC_prior_rank tr td,
 5019: table.LC_prior_match tr td {
 5020:   border: 1px solid #000000;
 5021: }
 5022: 
 5023: span.LC_nobreak {
 5024:   white-space: nowrap;
 5025: }
 5026: 
 5027: span.LC_cusr_emph {
 5028:   font-style: italic;
 5029: }
 5030: 
 5031: span.LC_cusr_subheading {
 5032:   font-weight: normal;
 5033:   font-size: 85%;
 5034: }
 5035: 
 5036: table.LC_docs_documents {
 5037:   background: #BBBBBB;
 5038:   border-width: 0px;
 5039:   border-collapse: collapse;
 5040: }
 5041: 
 5042: table.LC_docs_documents td.LC_docs_document {
 5043:   border: 2px solid black;
 5044:   padding: 4px;
 5045: }
 5046: 
 5047: .LC_docs_course_commands div {
 5048:   float: left;
 5049:   border: 4px solid #AAAAAA;
 5050:   padding: 4px;
 5051:   background: #DDDDCC;
 5052: }
 5053: 
 5054: .LC_docs_entry_move {
 5055:   border: 0px;
 5056:   border-collapse: collapse;
 5057: }
 5058: 
 5059: .LC_docs_entry_move td {
 5060:   border: 2px solid #BBBBBB;
 5061:   background: #DDDDDD;
 5062: }
 5063: 
 5064: .LC_docs_editor td.LC_docs_entry_commands {
 5065:   background: #DDDDDD;
 5066:   font-size: x-small;
 5067: }
 5068: .LC_docs_copy {
 5069:   color: #000099;
 5070: }
 5071: .LC_docs_cut {
 5072:   color: #550044;
 5073: }
 5074: .LC_docs_rename {
 5075:   color: #009900;
 5076: }
 5077: .LC_docs_remove {
 5078:   color: #990000;
 5079: }
 5080: 
 5081: .LC_docs_reinit_warn,
 5082: .LC_docs_ext_edit {
 5083:   font-size: x-small;
 5084: }
 5085: 
 5086: .LC_docs_editor td.LC_docs_entry_title,
 5087: .LC_docs_editor td.LC_docs_entry_icon {
 5088:   background: #FFFFBB;
 5089: }
 5090: .LC_docs_editor td.LC_docs_entry_parameter {
 5091:   background: #BBBBFF;
 5092:   font-size: x-small;
 5093:   white-space: nowrap;
 5094: }
 5095: 
 5096: table.LC_docs_adddocs td,
 5097: table.LC_docs_adddocs th {
 5098:   border: 1px solid #BBBBBB;
 5099:   padding: 4px;
 5100:   background: #DDDDDD;
 5101: }
 5102: 
 5103: table.LC_sty_begin {
 5104:   background: #BBFFBB;
 5105: }
 5106: table.LC_sty_end {
 5107:   background: #FFBBBB;
 5108: }
 5109: 
 5110: table.LC_double_column {
 5111:   border-width: 0px;
 5112:   border-collapse: collapse;
 5113:   width: 100%;
 5114:   padding: 2px;
 5115: }
 5116: 
 5117: table.LC_double_column tr td.LC_left_col {
 5118:   top: 2px;
 5119:   left: 2px;
 5120:   width: 47%;
 5121:   vertical-align: top;
 5122: }
 5123: 
 5124: table.LC_double_column tr td.LC_right_col {
 5125:   top: 2px;
 5126:   right: 2px; 
 5127:   width: 47%;
 5128:   vertical-align: top;
 5129: }
 5130: 
 5131: span.LC_role_level {
 5132:   font-weight: bold;
 5133: }
 5134: 
 5135: div.LC_left_float {
 5136:   float: left;
 5137:   padding-right: 5%;
 5138:   padding-bottom: 4px;
 5139: }
 5140: 
 5141: div.LC_clear_float_header {
 5142:   padding-bottom: 2px;
 5143: }
 5144: 
 5145: div.LC_clear_float_footer {
 5146:   padding-top: 10px;
 5147:   clear: both;
 5148: }
 5149: 
 5150: 
 5151: div.LC_grade_select_mode {
 5152:   font-family: $sans;
 5153: }
 5154: div.LC_grade_select_mode div div {
 5155:   margin: 5px;
 5156: }
 5157: div.LC_grade_select_mode_selector {
 5158:   margin: 5px;
 5159:   float: left;
 5160: }
 5161: div.LC_grade_select_mode_selector_header {
 5162:   font: bold medium $sans;
 5163: }
 5164: div.LC_grade_select_mode_type {
 5165:   clear: left;
 5166: }
 5167: 
 5168: div.LC_grade_show_user {
 5169:   margin-top: 20px;
 5170:   border: 1px solid black;
 5171: }
 5172: div.LC_grade_user_name {
 5173:   background: #DDDDEE;
 5174:   border-bottom: 1px solid black;
 5175:   font: bold large $sans;
 5176: }
 5177: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5178:   background: #DDEEDD;
 5179: }
 5180: 
 5181: div.LC_grade_show_problem,
 5182: div.LC_grade_submissions,
 5183: div.LC_grade_message_center,
 5184: div.LC_grade_info_links,
 5185: div.LC_grade_assign {
 5186:   margin: 5px;
 5187:   width: 99%;
 5188:   background: #FFFFFF;
 5189: }
 5190: div.LC_grade_show_problem_header,
 5191: div.LC_grade_submissions_header,
 5192: div.LC_grade_message_center_header,
 5193: div.LC_grade_assign_header {
 5194:   font: bold large $sans;
 5195: }
 5196: div.LC_grade_show_problem_problem,
 5197: div.LC_grade_submissions_body,
 5198: div.LC_grade_message_center_body,
 5199: div.LC_grade_assign_body {
 5200:   border: 1px solid black;
 5201:   width: 99%;
 5202:   background: #FFFFFF;
 5203: }
 5204: span.LC_grade_check_note {
 5205:   font: normal medium $sans;
 5206:   display: inline;
 5207:   position: absolute;
 5208:   right: 1em;
 5209: }
 5210: 
 5211: table.LC_scantron_action {
 5212:   width: 100%;
 5213: }
 5214: table.LC_scantron_action tr th {
 5215:   font: normal bold $sans;
 5216: }
 5217: 
 5218: div.LC_edit_problem_header, 
 5219: div.LC_edit_problem_footer {
 5220:   font: normal medium $sans;
 5221:   margin: 2px;
 5222: }
 5223: div.LC_edit_problem_header,
 5224: div.LC_edit_problem_header div,
 5225: div.LC_edit_problem_footer,
 5226: div.LC_edit_problem_footer div,
 5227: div.LC_edit_problem_editxml_header,
 5228: div.LC_edit_problem_editxml_header div {
 5229:   margin-top: 5px;
 5230: }
 5231: div.LC_edit_problem_header_edit_row {
 5232:   background: $tabbg;
 5233:   padding: 3px;
 5234:   margin-bottom: 5px;
 5235: }
 5236: div.LC_edit_problem_header_title {
 5237:   font: larger bold $sans;
 5238:   background: $tabbg;
 5239:   padding: 3px;
 5240: }
 5241: table.LC_edit_problem_header_title {
 5242:   font: larger bold $sans;
 5243:   width: 100%;
 5244:   border-color: $pgbg;
 5245:   border-style: solid;
 5246:   border-width: $border;
 5247: 
 5248:   background: $tabbg;
 5249:   border-collapse: collapse;
 5250:   padding: 0px
 5251: }
 5252: 
 5253: div.LC_edit_problem_discards {
 5254:   float: left;
 5255:   padding-bottom: 5px;
 5256: }
 5257: div.LC_edit_problem_saves {
 5258:   float: right;
 5259:   padding-bottom: 5px;
 5260: }
 5261: hr.LC_edit_problem_divide {
 5262:   clear: both;
 5263:   color: $tabbg;
 5264:   background-color: $tabbg;
 5265:   height: 3px;
 5266:   border: 0px;
 5267: }
 5268: END
 5269: }
 5270: 
 5271: =pod
 5272: 
 5273: =item * &headtag()
 5274: 
 5275: Returns a uniform footer for LON-CAPA web pages.
 5276: 
 5277: Inputs: $title - optional title for the head
 5278:         $head_extra - optional extra HTML to put inside the <head>
 5279:         $args - optional arguments
 5280:             force_register - if is true call registerurl so the remote is 
 5281:                              informed
 5282:             redirect       -> array ref of
 5283:                                    1- seconds before redirect occurs
 5284:                                    2- url to redirect to
 5285:                                    3- whether the side effect should occur
 5286:                            (side effect of setting 
 5287:                                $env{'internal.head.redirect'} to the url 
 5288:                                redirected too)
 5289:             domain         -> force to color decorate a page for a specific
 5290:                                domain
 5291:             function       -> force usage of a specific rolish color scheme
 5292:             bgcolor        -> override the default page bgcolor
 5293:             no_auto_mt_title
 5294:                            -> prevent &mt()ing the title arg
 5295: 
 5296: =cut
 5297: 
 5298: sub headtag {
 5299:     my ($title,$head_extra,$args) = @_;
 5300:     
 5301:     my $function = $args->{'function'} || &get_users_function();
 5302:     my $domain   = $args->{'domain'}   || &determinedomain();
 5303:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5304:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5305: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5306: 		   #time(),
 5307: 		   $env{'environment.color.timestamp'},
 5308: 		   $function,$domain,$bgcolor);
 5309: 
 5310:     $url = '/adm/css/'.&escape($url).'.css';
 5311: 
 5312:     my $result =
 5313: 	'<head>'.
 5314: 	&font_settings();
 5315: 
 5316:     if (!$args->{'frameset'}) {
 5317: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5318:     }
 5319:     if ($args->{'force_register'}) {
 5320: 	$result .= &Apache::lonmenu::registerurl(1);
 5321:     }
 5322:     if (!$args->{'no_nav_bar'} 
 5323: 	&& !$args->{'only_body'}
 5324: 	&& !$args->{'frameset'}) {
 5325: 	$result .= &help_menu_js();
 5326:     }
 5327: 
 5328:     if (ref($args->{'redirect'})) {
 5329: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5330: 	$url = &Apache::lonenc::check_encrypt($url);
 5331: 	if (!$inhibit_continue) {
 5332: 	    $env{'internal.head.redirect'} = $url;
 5333: 	}
 5334: 	$result.=<<ADDMETA
 5335: <meta http-equiv="pragma" content="no-cache" />
 5336: <meta http-equiv="Refresh" content="$time; url=$url" />
 5337: ADDMETA
 5338:     }
 5339:     if (!defined($title)) {
 5340: 	$title = 'The LearningOnline Network with CAPA';
 5341:     }
 5342:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5343:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5344: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5345: 	.$head_extra;
 5346:     return $result;
 5347: }
 5348: 
 5349: =pod
 5350: 
 5351: =item * &font_settings()
 5352: 
 5353: Returns neccessary <meta> to set the proper encoding
 5354: 
 5355: Inputs: none
 5356: 
 5357: =cut
 5358: 
 5359: sub font_settings {
 5360:     my $headerstring='';
 5361:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5362: 	$headerstring.=
 5363: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5364:     }
 5365:     return $headerstring;
 5366: }
 5367: 
 5368: =pod
 5369: 
 5370: =item * &xml_begin()
 5371: 
 5372: Returns the needed doctype and <html>
 5373: 
 5374: Inputs: none
 5375: 
 5376: =cut
 5377: 
 5378: sub xml_begin {
 5379:     my $output='';
 5380: 
 5381:     if ($env{'internal.start_page'}==1) {
 5382: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5383:     }
 5384: 
 5385:     if ($env{'browser.mathml'}) {
 5386: 	$output='<?xml version="1.0"?>'
 5387:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5388: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5389:             
 5390: #	    .'<!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">] >'
 5391: 	    .'<!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">'
 5392:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5393: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5394:     } else {
 5395: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 5396:     }
 5397:     return $output;
 5398: }
 5399: 
 5400: =pod
 5401: 
 5402: =item * &endheadtag()
 5403: 
 5404: Returns a uniform </head> for LON-CAPA web pages.
 5405: 
 5406: Inputs: none
 5407: 
 5408: =cut
 5409: 
 5410: sub endheadtag {
 5411:     return '</head>';
 5412: }
 5413: 
 5414: =pod
 5415: 
 5416: =item * &head()
 5417: 
 5418: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5419: 
 5420: Inputs:
 5421: 
 5422: =over 4
 5423: 
 5424: $title - optional title for the page
 5425: 
 5426: $head_extra - optional extra HTML to put inside the <head>
 5427: 
 5428: =back
 5429: 
 5430: =cut
 5431: 
 5432: sub head {
 5433:     my ($title,$head_extra,$args) = @_;
 5434:     return &headtag($title,$head_extra,$args).&endheadtag();
 5435: }
 5436: 
 5437: =pod
 5438: 
 5439: =item * &start_page()
 5440: 
 5441: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5442: 
 5443: Inputs:
 5444: 
 5445: =over 4
 5446: 
 5447: $title - optional title for the page
 5448: 
 5449: $head_extra - optional extra HTML to incude inside the <head>
 5450: 
 5451: $args - additional optional args supported are:
 5452: 
 5453: =over 8
 5454: 
 5455:              only_body      -> is true will set &bodytag() onlybodytag
 5456:                                     arg on
 5457:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5458:              add_entries    -> additional attributes to add to the  <body>
 5459:              domain         -> force to color decorate a page for a 
 5460:                                     specific domain
 5461:              function       -> force usage of a specific rolish color
 5462:                                     scheme
 5463:              redirect       -> see &headtag()
 5464:              bgcolor        -> override the default page bg color
 5465:              js_ready       -> return a string ready for being used in 
 5466:                                     a javascript writeln
 5467:              html_encode    -> return a string ready for being used in 
 5468:                                     a html attribute
 5469:              force_register -> if is true will turn on the &bodytag()
 5470:                                     $forcereg arg
 5471:              body_title     -> alternate text to use instead of $title
 5472:                                     in the title box that appears, this text
 5473:                                     is not auto translated like the $title is
 5474:              frameset       -> if true will start with a <frameset>
 5475:                                     rather than <body>
 5476:              no_title       -> if true the title bar won't be shown
 5477:              skip_phases    -> hash ref of 
 5478:                                     head -> skip the <html><head> generation
 5479:                                     body -> skip all <body> generation
 5480:              no_inline_link -> if true and in remote mode, don't show the 
 5481:                                     'Switch To Inline Menu' link
 5482:              no_auto_mt_title -> prevent &mt()ing the title arg
 5483:              inherit_jsmath -> when creating popup window in a page,
 5484:                                     should it have jsmath forced on by the
 5485:                                     current page
 5486: 
 5487: =back
 5488: 
 5489: =back
 5490: 
 5491: =cut
 5492: 
 5493: sub start_page {
 5494:     my ($title,$head_extra,$args) = @_;
 5495:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5496:     my %head_args;
 5497:     foreach my $arg ('redirect','force_register','domain','function',
 5498: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5499: 		     'no_auto_mt_title') {
 5500: 	if (defined($args->{$arg})) {
 5501: 	    $head_args{$arg} = $args->{$arg};
 5502: 	}
 5503:     }
 5504: 
 5505:     $env{'internal.start_page'}++;
 5506:     my $result;
 5507:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 5508: 	$result.=
 5509: 	    &xml_begin().
 5510: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 5511:     }
 5512:     
 5513:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 5514: 	if ($args->{'frameset'}) {
 5515: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 5516: 						$args->{'add_entries'});
 5517: 	    $result .= "\n<frameset $attr_string>\n";
 5518: 	} else {
 5519: 	    $result .=
 5520: 		&bodytag($title, 
 5521: 			 $args->{'function'},       $args->{'add_entries'},
 5522: 			 $args->{'only_body'},      $args->{'domain'},
 5523: 			 $args->{'force_register'}, $args->{'body_title'},
 5524: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 5525: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 5526: 			 $args);
 5527: 	}
 5528:     }
 5529: 
 5530:     if ($args->{'js_ready'}) {
 5531: 	$result = &js_ready($result);
 5532:     }
 5533:     if ($args->{'html_encode'}) {
 5534: 	$result = &html_encode($result);
 5535:     }
 5536:     return $result;
 5537: }
 5538: 
 5539: 
 5540: =pod
 5541: 
 5542: =item * &head()
 5543: 
 5544: Returns a complete </body></html> section for LON-CAPA web pages.
 5545: 
 5546: Inputs:         $args - additional optional args supported are:
 5547:                  js_ready     -> return a string ready for being used in 
 5548:                                  a javascript writeln
 5549:                  html_encode  -> return a string ready for being used in 
 5550:                                  a html attribute
 5551:                  frameset     -> if true will start with a <frameset>
 5552:                                  rather than <body>
 5553:                  dicsussion   -> if true will get discussion from
 5554:                                   lonxml::xmlend
 5555:                                  (you can pass the target and parser arguments
 5556:                                   through optional 'target' and 'parser' args
 5557:                                   to this routine)
 5558: 
 5559: =cut
 5560: 
 5561: sub end_page {
 5562:     my ($args) = @_;
 5563:     $env{'internal.end_page'}++;
 5564:     my $result;
 5565:     if ($args->{'discussion'}) {
 5566: 	my ($target,$parser);
 5567: 	if (ref($args->{'discussion'})) {
 5568: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 5569: 				$args->{'discussion'}{'parser'});
 5570: 	}
 5571: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 5572:     }
 5573: 
 5574:     if ($args->{'frameset'}) {
 5575: 	$result .= '</frameset>';
 5576:     } else {
 5577: 	$result .= &endbodytag($args);
 5578:     }
 5579:     $result .= "\n</html>";
 5580: 
 5581:     if ($args->{'js_ready'}) {
 5582: 	$result = &js_ready($result);
 5583:     }
 5584: 
 5585:     if ($args->{'html_encode'}) {
 5586: 	$result = &html_encode($result);
 5587:     }
 5588: 
 5589:     return $result;
 5590: }
 5591: 
 5592: sub html_encode {
 5593:     my ($result) = @_;
 5594: 
 5595:     $result = &HTML::Entities::encode($result,'<>&"');
 5596:     
 5597:     return $result;
 5598: }
 5599: sub js_ready {
 5600:     my ($result) = @_;
 5601: 
 5602:     $result =~ s/[\n\r]/ /xmsg;
 5603:     $result =~ s/\\/\\\\/xmsg;
 5604:     $result =~ s/'/\\'/xmsg;
 5605:     $result =~ s{</}{<\\/}xmsg;
 5606:     
 5607:     return $result;
 5608: }
 5609: 
 5610: sub validate_page {
 5611:     if (  exists($env{'internal.start_page'})
 5612: 	  &&     $env{'internal.start_page'} > 1) {
 5613: 	&Apache::lonnet::logthis('start_page called multiple times '.
 5614: 				 $env{'internal.start_page'}.' '.
 5615: 				 $ENV{'request.filename'});
 5616:     }
 5617:     if (  exists($env{'internal.end_page'})
 5618: 	  &&     $env{'internal.end_page'} > 1) {
 5619: 	&Apache::lonnet::logthis('end_page called multiple times '.
 5620: 				 $env{'internal.end_page'}.' '.
 5621: 				 $env{'request.filename'});
 5622:     }
 5623:     if (     exists($env{'internal.start_page'})
 5624: 	&& ! exists($env{'internal.end_page'})) {
 5625: 	&Apache::lonnet::logthis('start_page called without end_page '.
 5626: 				 $env{'request.filename'});
 5627:     }
 5628:     if (   ! exists($env{'internal.start_page'})
 5629: 	&&   exists($env{'internal.end_page'})) {
 5630: 	&Apache::lonnet::logthis('end_page called without start_page'.
 5631: 				 $env{'request.filename'});
 5632:     }
 5633: }
 5634: 
 5635: sub simple_error_page {
 5636:     my ($r,$title,$msg) = @_;
 5637:     my $page =
 5638: 	&Apache::loncommon::start_page($title).
 5639: 	&mt($msg).
 5640: 	&Apache::loncommon::end_page();
 5641:     if (ref($r)) {
 5642: 	$r->print($page);
 5643: 	return;
 5644:     }
 5645:     return $page;
 5646: }
 5647: 
 5648: {
 5649:     my @row_count;
 5650:     sub start_data_table {
 5651: 	my ($add_class) = @_;
 5652: 	my $css_class = (join(' ','LC_data_table',$add_class));
 5653: 	unshift(@row_count,0);
 5654: 	return '<table class="'.$css_class.'">'."\n";
 5655:     }
 5656: 
 5657:     sub end_data_table {
 5658: 	shift(@row_count);
 5659: 	return '</table>'."\n";;
 5660:     }
 5661: 
 5662:     sub start_data_table_row {
 5663: 	my ($add_class) = @_;
 5664: 	$row_count[0]++;
 5665: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5666: 	$css_class = (join(' ',$css_class,$add_class));
 5667: 	return  '<tr class="'.$css_class.'">'."\n";;
 5668:     }
 5669:     
 5670:     sub continue_data_table_row {
 5671: 	my ($add_class) = @_;
 5672: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5673: 	$css_class = (join(' ',$css_class,$add_class));
 5674: 	return  '<tr class="'.$css_class.'">'."\n";;
 5675:     }
 5676: 
 5677:     sub end_data_table_row {
 5678: 	return '</tr>'."\n";;
 5679:     }
 5680: 
 5681:     sub start_data_table_empty_row {
 5682: 	$row_count[0]++;
 5683: 	return  '<tr class="LC_empty_row" >'."\n";;
 5684:     }
 5685: 
 5686:     sub end_data_table_empty_row {
 5687: 	return '</tr>'."\n";;
 5688:     }
 5689: 
 5690:     sub start_data_table_header_row {
 5691: 	return  '<tr class="LC_header_row">'."\n";;
 5692:     }
 5693: 
 5694:     sub end_data_table_header_row {
 5695: 	return '</tr>'."\n";;
 5696:     }
 5697: }
 5698: 
 5699: =pod
 5700: 
 5701: =item * &inhibit_menu_check($arg)
 5702: 
 5703: Checks for a inhibitmenu state and generates output to preserve it
 5704: 
 5705: Inputs:         $arg - can be any of
 5706:                      - undef - in which case the return value is a string 
 5707:                                to add  into arguments list of a uri
 5708:                      - 'input' - in which case the return value is a HTML
 5709:                                  <form> <input> field of type hidden to
 5710:                                  preserve the value
 5711:                      - a url - in which case the return value is the url with
 5712:                                the neccesary cgi args added to preserve the
 5713:                                inhibitmenu state
 5714:                      - a ref to a url - no return value, but the string is
 5715:                                         updated to include the neccessary cgi
 5716:                                         args to preserve the inhibitmenu state
 5717: 
 5718: =cut
 5719: 
 5720: sub inhibit_menu_check {
 5721:     my ($arg) = @_;
 5722:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5723:     if ($arg eq 'input') {
 5724: 	if ($env{'form.inhibitmenu'}) {
 5725: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 5726: 	} else {
 5727: 	    return
 5728: 	}
 5729:     }
 5730:     if ($env{'form.inhibitmenu'}) {
 5731: 	if (ref($arg)) {
 5732: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5733: 	} elsif ($arg eq '') {
 5734: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 5735: 	} else {
 5736: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5737: 	}
 5738:     }
 5739:     if (!ref($arg)) {
 5740: 	return $arg;
 5741:     }
 5742: }
 5743: 
 5744: ###############################################
 5745: 
 5746: =pod
 5747: 
 5748: =back
 5749: 
 5750: =head1 User Information Routines
 5751: 
 5752: =over 4
 5753: 
 5754: =item * &get_users_function()
 5755: 
 5756: Used by &bodytag to determine the current users primary role.
 5757: Returns either 'student','coordinator','admin', or 'author'.
 5758: 
 5759: =cut
 5760: 
 5761: ###############################################
 5762: sub get_users_function {
 5763:     my $function = 'student';
 5764:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 5765:         $function='coordinator';
 5766:     }
 5767:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 5768:         $function='admin';
 5769:     }
 5770:     if (($env{'request.role'}=~/^(au|ca)/) ||
 5771:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 5772:         $function='author';
 5773:     }
 5774:     return $function;
 5775: }
 5776: 
 5777: ###############################################
 5778: 
 5779: =pod
 5780: 
 5781: =item * &check_user_status()
 5782: 
 5783: Determines current status of supplied role for a
 5784: specific user. Roles can be active, previous or future.
 5785: 
 5786: Inputs: 
 5787: user's domain, user's username, course's domain,
 5788: course's number, optional section ID.
 5789: 
 5790: Outputs:
 5791: role status: active, previous or future. 
 5792: 
 5793: =cut
 5794: 
 5795: sub check_user_status {
 5796:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 5797:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 5798:     my @uroles = keys %userinfo;
 5799:     my $srchstr;
 5800:     my $active_chk = 'none';
 5801:     my $now = time;
 5802:     if (@uroles > 0) {
 5803:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 5804:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 5805:         } else {
 5806:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 5807:         }
 5808:         if (grep/^\Q$srchstr\E$/,@uroles) {
 5809:             my $role_end = 0;
 5810:             my $role_start = 0;
 5811:             $active_chk = 'active';
 5812:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 5813:                 $role_end = $1;
 5814:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 5815:                     $role_start = $1;
 5816:                 }
 5817:             }
 5818:             if ($role_start > 0) {
 5819:                 if ($now < $role_start) {
 5820:                     $active_chk = 'future';
 5821:                 }
 5822:             }
 5823:             if ($role_end > 0) {
 5824:                 if ($now > $role_end) {
 5825:                     $active_chk = 'previous';
 5826:                 }
 5827:             }
 5828:         }
 5829:     }
 5830:     return $active_chk;
 5831: }
 5832: 
 5833: ###############################################
 5834: 
 5835: =pod
 5836: 
 5837: =item * &get_sections()
 5838: 
 5839: Determines all the sections for a course including
 5840: sections with students and sections containing other roles.
 5841: Incoming parameters: 
 5842: 
 5843: 1. domain
 5844: 2. course number 
 5845: 3. reference to array containing roles for which sections should 
 5846: be gathered (optional).
 5847: 4. reference to array containing status types for which sections 
 5848: should be gathered (optional).
 5849: 
 5850: If the third argument is undefined, sections are gathered for any role. 
 5851: If the fourth argument is undefined, sections are gathered for any status.
 5852: Permissible values are 'active' or 'future' or 'previous'.
 5853:  
 5854: Returns section hash (keys are section IDs, values are
 5855: number of users in each section), subject to the
 5856: optional roles filter, optional status filter 
 5857: 
 5858: =cut
 5859: 
 5860: ###############################################
 5861: sub get_sections {
 5862:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 5863:     if (!defined($cdom) || !defined($cnum)) {
 5864:         my $cid =  $env{'request.course.id'};
 5865: 
 5866: 	return if (!defined($cid));
 5867: 
 5868:         $cdom = $env{'course.'.$cid.'.domain'};
 5869:         $cnum = $env{'course.'.$cid.'.num'};
 5870:     }
 5871: 
 5872:     my %sectioncount;
 5873:     my $now = time;
 5874: 
 5875:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 5876: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 5877: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 5878: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 5879:         my $start_index = &Apache::loncoursedata::CL_START();
 5880:         my $end_index = &Apache::loncoursedata::CL_END();
 5881:         my $status;
 5882: 	while (my ($student,$data) = each(%$classlist)) {
 5883: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 5884: 				                     $data->[$status_index],
 5885:                                                      $data->[$start_index],
 5886:                                                      $data->[$end_index]);
 5887:             if ($stu_status eq 'Active') {
 5888:                 $status = 'active';
 5889:             } elsif ($end < $now) {
 5890:                 $status = 'previous';
 5891:             } elsif ($start > $now) {
 5892:                 $status = 'future';
 5893:             } 
 5894: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 5895:                 if ((!defined($possible_status)) || (($status ne '') && 
 5896:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 5897: 		    $sectioncount{$section}++;
 5898:                 }
 5899: 	    }
 5900: 	}
 5901:     }
 5902:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 5903:     foreach my $user (sort(keys(%courseroles))) {
 5904: 	if ($user !~ /^(\w{2})/) { next; }
 5905: 	my ($role) = ($user =~ /^(\w{2})/);
 5906: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 5907: 	my ($section,$status);
 5908: 	if ($role eq 'cr' &&
 5909: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 5910: 	    $section=$1;
 5911: 	}
 5912: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 5913: 	if (!defined($section) || $section eq '-1') { next; }
 5914:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 5915:         if ($end == -1 && $start == -1) {
 5916:             next; #deleted role
 5917:         }
 5918:         if (!defined($possible_status)) { 
 5919:             $sectioncount{$section}++;
 5920:         } else {
 5921:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 5922:                 $status = 'active';
 5923:             } elsif ($end < $now) {
 5924:                 $status = 'future';
 5925:             } elsif ($start > $now) {
 5926:                 $status = 'previous';
 5927:             }
 5928:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 5929:                 $sectioncount{$section}++;
 5930:             }
 5931:         }
 5932:     }
 5933:     return %sectioncount;
 5934: }
 5935: 
 5936: ###############################################
 5937: 
 5938: =pod
 5939: 
 5940: =item * &get_course_users()
 5941: 
 5942: Retrieves usernames:domains for users in the specified course
 5943: with specific role(s), and access status. 
 5944: 
 5945: Incoming parameters:
 5946: 1. course domain
 5947: 2. course number
 5948: 3. access status: users must have - either active, 
 5949: previous, future, or all.
 5950: 4. reference to array of permissible roles
 5951: 5. reference to array of section restrictions (optional)
 5952: 6. reference to results object (hash of hashes).
 5953: 7. reference to optional userdata hash
 5954: 8. reference to optional statushash
 5955: 9. flag if privileged users (except those set to unhide in
 5956:    course settings) should be excluded    
 5957: Keys of top level results hash are roles.
 5958: Keys of inner hashes are username:domain, with 
 5959: values set to access type.
 5960: Optional userdata hash returns an array with arguments in the 
 5961: same order as loncoursedata::get_classlist() for student data.
 5962: 
 5963: Optional statushash returns
 5964: 
 5965: Entries for end, start, section and status are blank because
 5966: of the possibility of multiple values for non-student roles.
 5967: 
 5968: =cut
 5969: 
 5970: ###############################################
 5971: 
 5972: sub get_course_users {
 5973:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 5974:     my %idx = ();
 5975:     my %seclists;
 5976: 
 5977:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 5978:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 5979:     $idx{end} = &Apache::loncoursedata::CL_END();
 5980:     $idx{start} = &Apache::loncoursedata::CL_START();
 5981:     $idx{id} = &Apache::loncoursedata::CL_ID();
 5982:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 5983:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 5984:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 5985: 
 5986:     if (grep(/^st$/,@{$roles})) {
 5987:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 5988:         my $now = time;
 5989:         foreach my $student (keys(%{$classlist})) {
 5990:             my $match = 0;
 5991:             my $secmatch = 0;
 5992:             my $section = $$classlist{$student}[$idx{section}];
 5993:             my $status = $$classlist{$student}[$idx{status}];
 5994:             if ($section eq '') {
 5995:                 $section = 'none';
 5996:             }
 5997:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 5998:                 if (grep(/^all$/,@{$sections})) {
 5999:                     $secmatch = 1;
 6000:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6001:                     if (grep(/^none$/,@{$sections})) {
 6002:                         $secmatch = 1;
 6003:                     }
 6004:                 } else {  
 6005: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6006: 		        $secmatch = 1;
 6007:                     }
 6008: 		}
 6009:                 if (!$secmatch) {
 6010:                     next;
 6011:                 }
 6012:             }
 6013:             if (defined($$types{'active'})) {
 6014:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6015:                     push(@{$$users{st}{$student}},'active');
 6016:                     $match = 1;
 6017:                 }
 6018:             }
 6019:             if (defined($$types{'previous'})) {
 6020:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6021:                     push(@{$$users{st}{$student}},'previous');
 6022:                     $match = 1;
 6023:                 }
 6024:             }
 6025:             if (defined($$types{'future'})) {
 6026:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6027:                     push(@{$$users{st}{$student}},'future');
 6028:                     $match = 1;
 6029:                 }
 6030:             }
 6031:             if ($match) {
 6032:                 push(@{$seclists{$student}},$section);
 6033:                 if (ref($userdata) eq 'HASH') {
 6034:                     $$userdata{$student} = $$classlist{$student};
 6035:                 }
 6036:                 if (ref($statushash) eq 'HASH') {
 6037:                     $statushash->{$student}{'st'}{$section} = $status;
 6038:                 }
 6039:             }
 6040:         }
 6041:     }
 6042:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6043:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6044:         my $now = time;
 6045:         my %displaystatus = ( previous => 'Expired',
 6046:                               active   => 'Active',
 6047:                               future   => 'Future',
 6048:                             );
 6049:         my %nothide;
 6050:         if ($hidepriv) {
 6051:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6052:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6053:                 if ($user !~ /:/) {
 6054:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6055:                 } else {
 6056:                     $nothide{$user} = 1;
 6057:                 }
 6058:             }
 6059:         }
 6060:         foreach my $person (sort(keys(%coursepersonnel))) {
 6061:             my $match = 0;
 6062:             my $secmatch = 0;
 6063:             my $status;
 6064:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6065:             $user =~ s/:$//;
 6066:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6067:             if ($end == -1 || $start == -1) {
 6068:                 next;
 6069:             }
 6070:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6071:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6072:                 my ($uname,$udom) = split(/:/,$user);
 6073:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6074:                     if (grep(/^all$/,@{$sections})) {
 6075:                         $secmatch = 1;
 6076:                     } elsif ($usec eq '') {
 6077:                         if (grep(/^none$/,@{$sections})) {
 6078:                             $secmatch = 1;
 6079:                         }
 6080:                     } else {
 6081:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6082:                             $secmatch = 1;
 6083:                         }
 6084:                     }
 6085:                     if (!$secmatch) {
 6086:                         next;
 6087:                     }
 6088:                 }
 6089:                 if ($usec eq '') {
 6090:                     $usec = 'none';
 6091:                 }
 6092:                 if ($uname ne '' && $udom ne '') {
 6093:                     if ($hidepriv) {
 6094:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6095:                             (!$nothide{$uname.':'.$udom})) {
 6096:                             next;
 6097:                         }
 6098:                     }
 6099:                     if ($end > 0 && $end < $now) {
 6100:                         $status = 'previous';
 6101:                     } elsif ($start > $now) {
 6102:                         $status = 'future';
 6103:                     } else {
 6104:                         $status = 'active';
 6105:                     }
 6106:                     foreach my $type (keys(%{$types})) { 
 6107:                         if ($status eq $type) {
 6108:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6109:                                 push(@{$$users{$role}{$user}},$type);
 6110:                             }
 6111:                             $match = 1;
 6112:                         }
 6113:                     }
 6114:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6115:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6116: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6117:                         }
 6118:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6119:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6120:                         }
 6121:                         if (ref($statushash) eq 'HASH') {
 6122:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6123:                         }
 6124:                     }
 6125:                 }
 6126:             }
 6127:         }
 6128:         if (grep(/^ow$/,@{$roles})) {
 6129:             if ((defined($cdom)) && (defined($cnum))) {
 6130:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6131:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6132:                     my $owner = $csettings{'internal.courseowner'};
 6133:                     next if ($owner eq '');
 6134:                     my ($ownername,$ownerdom);
 6135:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6136:                         $ownername = $1;
 6137:                         $ownerdom = $2;
 6138:                     } else {
 6139:                         $ownername = $owner;
 6140:                         $ownerdom = $cdom;
 6141:                         $owner = $ownername.':'.$ownerdom;
 6142:                     }
 6143:                     @{$$users{'ow'}{$owner}} = 'any';
 6144:                     if (defined($userdata) && 
 6145: 			!exists($$userdata{$owner})) {
 6146: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6147:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6148:                             push(@{$seclists{$owner}},'none');
 6149:                         }
 6150:                         if (ref($statushash) eq 'HASH') {
 6151:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6152:                         }
 6153: 		    }
 6154:                 }
 6155:             }
 6156:         }
 6157:         foreach my $user (keys(%seclists)) {
 6158:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6159:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6160:         }
 6161:     }
 6162:     return;
 6163: }
 6164: 
 6165: sub get_user_info {
 6166:     my ($udom,$uname,$idx,$userdata) = @_;
 6167:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6168: 	&plainname($uname,$udom,'lastname');
 6169:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6170:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6171:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6172:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6173:     return;
 6174: }
 6175: 
 6176: ###############################################
 6177: 
 6178: =pod
 6179: 
 6180: =item * &get_user_quota()
 6181: 
 6182: Retrieves quota assigned for storage of portfolio files for a user  
 6183: 
 6184: Incoming parameters:
 6185: 1. user's username
 6186: 2. user's domain
 6187: 
 6188: Returns:
 6189: 1. Disk quota (in Mb) assigned to student.
 6190: 2. (Optional) Type of setting: custom or default
 6191:    (individually assigned or default for user's 
 6192:    institutional status).
 6193: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6194:    or student - types as defined in localenroll::inst_usertypes 
 6195:    for user's domain, which determines default quota for user.
 6196: 4. (Optional) - Default quota which would apply to the user.
 6197: 
 6198: If a value has been stored in the user's environment, 
 6199: it will return that, otherwise it returns the maximal default
 6200: defined for the user's instituional status(es) in the domain.
 6201: 
 6202: =cut
 6203: 
 6204: ###############################################
 6205: 
 6206: 
 6207: sub get_user_quota {
 6208:     my ($uname,$udom) = @_;
 6209:     my ($quota,$quotatype,$settingstatus,$defquota);
 6210:     if (!defined($udom)) {
 6211:         $udom = $env{'user.domain'};
 6212:     }
 6213:     if (!defined($uname)) {
 6214:         $uname = $env{'user.name'};
 6215:     }
 6216:     if (($udom eq '' || $uname eq '') ||
 6217:         ($udom eq 'public') && ($uname eq 'public')) {
 6218:         $quota = 0;
 6219:         $quotatype = 'default';
 6220:         $defquota = 0; 
 6221:     } else {
 6222:         my $inststatus;
 6223:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6224:             $quota = $env{'environment.portfolioquota'};
 6225:             $inststatus = $env{'environment.inststatus'};
 6226:         } else {
 6227:             my %userenv = 
 6228:                 &Apache::lonnet::get('environment',['portfolioquota',
 6229:                                      'inststatus'],$udom,$uname);
 6230:             my ($tmp) = keys(%userenv);
 6231:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6232:                 $quota = $userenv{'portfolioquota'};
 6233:                 $inststatus = $userenv{'inststatus'};
 6234:             } else {
 6235:                 undef(%userenv);
 6236:             }
 6237:         }
 6238:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6239:         if ($quota eq '') {
 6240:             $quota = $defquota;
 6241:             $quotatype = 'default';
 6242:         } else {
 6243:             $quotatype = 'custom';
 6244:         }
 6245:     }
 6246:     if (wantarray) {
 6247:         return ($quota,$quotatype,$settingstatus,$defquota);
 6248:     } else {
 6249:         return $quota;
 6250:     }
 6251: }
 6252: 
 6253: ###############################################
 6254: 
 6255: =pod
 6256: 
 6257: =item * &default_quota()
 6258: 
 6259: Retrieves default quota assigned for storage of user portfolio files,
 6260: given an (optional) user's institutional status.
 6261: 
 6262: Incoming parameters:
 6263: 1. domain
 6264: 2. (Optional) institutional status(es).  This is a : separated list of 
 6265:    status types (e.g., faculty, staff, student etc.)
 6266:    which apply to the user for whom the default is being retrieved.
 6267:    If the institutional status string in undefined, the domain
 6268:    default quota will be returned. 
 6269: 
 6270: Returns:
 6271: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6272: 2. (Optional) institutional type which determined the value of the
 6273:    default quota.
 6274: 
 6275: If a value has been stored in the domain's configuration db,
 6276: it will return that, otherwise it returns 20 (for backwards 
 6277: compatibility with domains which have not set up a configuration
 6278: db file; the original statically defined portfolio quota was 20 Mb). 
 6279: 
 6280: If the user's status includes multiple types (e.g., staff and student),
 6281: the largest default quota which applies to the user determines the
 6282: default quota returned.
 6283: 
 6284: =cut
 6285: 
 6286: ###############################################
 6287: 
 6288: 
 6289: sub default_quota {
 6290:     my ($udom,$inststatus) = @_;
 6291:     my ($defquota,$settingstatus);
 6292:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6293:                                             ['quotas'],$udom);
 6294:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6295:         if ($inststatus ne '') {
 6296:             my @statuses = split(/:/,$inststatus);
 6297:             foreach my $item (@statuses) {
 6298:                 if ($quotahash{'quotas'}{$item} ne '') {
 6299:                     if ($defquota eq '') {
 6300:                         $defquota = $quotahash{'quotas'}{$item};
 6301:                         $settingstatus = $item;
 6302:                     } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6303:                         $defquota = $quotahash{'quotas'}{$item};
 6304:                         $settingstatus = $item;
 6305:                     }
 6306:                 }
 6307:             }
 6308:         }
 6309:         if ($defquota eq '') {
 6310:             $defquota = $quotahash{'quotas'}{'default'};
 6311:             $settingstatus = 'default';
 6312:         }
 6313:     } else {
 6314:         $settingstatus = 'default';
 6315:         $defquota = 20;
 6316:     }
 6317:     if (wantarray) {
 6318:         return ($defquota,$settingstatus);
 6319:     } else {
 6320:         return $defquota;
 6321:     }
 6322: }
 6323: 
 6324: sub get_secgrprole_info {
 6325:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6326:     my %sections_count = &get_sections($cdom,$cnum);
 6327:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6328:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6329:     my @groups = sort(keys(%curr_groups));
 6330:     my $allroles = [];
 6331:     my $rolehash;
 6332:     my $accesshash = {
 6333:                      active => 'Currently has access',
 6334:                      future => 'Will have future access',
 6335:                      previous => 'Previously had access',
 6336:                   };
 6337:     if ($needroles) {
 6338:         $rolehash = {'all' => 'all'};
 6339:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6340: 	if (&Apache::lonnet::error(%user_roles)) {
 6341: 	    undef(%user_roles);
 6342: 	}
 6343:         foreach my $item (keys(%user_roles)) {
 6344:             my ($role)=split(/\:/,$item,2);
 6345:             if ($role eq 'cr') { next; }
 6346:             if ($role =~ /^cr/) {
 6347:                 $$rolehash{$role} = (split('/',$role))[3];
 6348:             } else {
 6349:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6350:             }
 6351:         }
 6352:         foreach my $key (sort(keys(%{$rolehash}))) {
 6353:             push(@{$allroles},$key);
 6354:         }
 6355:         push (@{$allroles},'st');
 6356:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6357:     }
 6358:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6359: }
 6360: 
 6361: sub user_picker {
 6362:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6363:     my $currdom = $dom;
 6364:     my %curr_selected = (
 6365:                         srchin => 'dom',
 6366:                         srchby => 'lastname',
 6367:                       );
 6368:     my $srchterm;
 6369:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6370:         if ($srch->{'srchby'} ne '') {
 6371:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6372:         }
 6373:         if ($srch->{'srchin'} ne '') {
 6374:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6375:         }
 6376:         if ($srch->{'srchtype'} ne '') {
 6377:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6378:         }
 6379:         if ($srch->{'srchdomain'} ne '') {
 6380:             $currdom = $srch->{'srchdomain'};
 6381:         }
 6382:         $srchterm = $srch->{'srchterm'};
 6383:     }
 6384:     my %lt=&Apache::lonlocal::texthash(
 6385:                     'usr'       => 'Search criteria',
 6386:                     'doma'      => 'Domain/institution to search',
 6387:                     'uname'     => 'username',
 6388:                     'lastname'  => 'last name',
 6389:                     'lastfirst' => 'last name, first name',
 6390:                     'crs'       => 'in this course',
 6391:                     'dom'       => 'in selected LON-CAPA domain', 
 6392:                     'alc'       => 'all LON-CAPA',
 6393:                     'instd'     => 'in institutional directory for selected domain',
 6394:                     'exact'     => 'is',
 6395:                     'contains'  => 'contains',
 6396:                     'begins'    => 'begins with',
 6397:                     'youm'      => "You must include some text to search for.",
 6398:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6399:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6400:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6401:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6402:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6403:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6404:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6405:                                        );
 6406:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6407:     my $srchinsel = ' <select name="srchin">';
 6408: 
 6409:     my @srchins = ('crs','dom','alc','instd');
 6410: 
 6411:     foreach my $option (@srchins) {
 6412:         # FIXME 'alc' option unavailable until 
 6413:         #       loncreateuser::print_user_query_page()
 6414:         #       has been completed.
 6415:         next if ($option eq 'alc');
 6416:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6417:         if ($curr_selected{'srchin'} eq $option) {
 6418:             $srchinsel .= ' 
 6419:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6420:         } else {
 6421:             $srchinsel .= '
 6422:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6423:         }
 6424:     }
 6425:     $srchinsel .= "\n  </select>\n";
 6426: 
 6427:     my $srchbysel =  ' <select name="srchby">';
 6428:     foreach my $option ('lastname','lastfirst','uname') {
 6429:         if ($curr_selected{'srchby'} eq $option) {
 6430:             $srchbysel .= '
 6431:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6432:         } else {
 6433:             $srchbysel .= '
 6434:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6435:          }
 6436:     }
 6437:     $srchbysel .= "\n  </select>\n";
 6438: 
 6439:     my $srchtypesel = ' <select name="srchtype">';
 6440:     foreach my $option ('begins','contains','exact') {
 6441:         if ($curr_selected{'srchtype'} eq $option) {
 6442:             $srchtypesel .= '
 6443:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6444:         } else {
 6445:             $srchtypesel .= '
 6446:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6447:         }
 6448:     }
 6449:     $srchtypesel .= "\n  </select>\n";
 6450: 
 6451:     my ($newuserscript,$new_user_create);
 6452: 
 6453:     if ($forcenewuser) {
 6454:         if (ref($srch) eq 'HASH') {
 6455:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 6456:                 if ($cancreate) {
 6457:                     $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>';
 6458:                 } else {
 6459:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6460:                     my %usertypetext = (
 6461:                         official   => 'institutional',
 6462:                         unofficial => 'non-institutional',
 6463:                     );
 6464:                     $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 />';
 6465:                 }
 6466:             }
 6467:         }
 6468: 
 6469:         $newuserscript = <<"ENDSCRIPT";
 6470: 
 6471: function setSearch(createnew,callingForm) {
 6472:     if (createnew == 1) {
 6473:         for (var i=0; i<callingForm.srchby.length; i++) {
 6474:             if (callingForm.srchby.options[i].value == 'uname') {
 6475:                 callingForm.srchby.selectedIndex = i;
 6476:             }
 6477:         }
 6478:         for (var i=0; i<callingForm.srchin.length; i++) {
 6479:             if ( callingForm.srchin.options[i].value == 'dom') {
 6480: 		callingForm.srchin.selectedIndex = i;
 6481:             }
 6482:         }
 6483:         for (var i=0; i<callingForm.srchtype.length; i++) {
 6484:             if (callingForm.srchtype.options[i].value == 'exact') {
 6485:                 callingForm.srchtype.selectedIndex = i;
 6486:             }
 6487:         }
 6488:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 6489:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 6490:                 callingForm.srchdomain.selectedIndex = i;
 6491:             }
 6492:         }
 6493:     }
 6494: }
 6495: ENDSCRIPT
 6496: 
 6497:     }
 6498: 
 6499:     my $output = <<"END_BLOCK";
 6500: <script type="text/javascript">
 6501: function validateEntry(callingForm) {
 6502: 
 6503:     var checkok = 1;
 6504:     var srchin;
 6505:     for (var i=0; i<callingForm.srchin.length; i++) {
 6506: 	if ( callingForm.srchin[i].checked ) {
 6507: 	    srchin = callingForm.srchin[i].value;
 6508: 	}
 6509:     }
 6510: 
 6511:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 6512:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 6513:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 6514:     var srchterm =  callingForm.srchterm.value;
 6515:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 6516:     var msg = "";
 6517: 
 6518:     if (srchterm == "") {
 6519:         checkok = 0;
 6520:         msg += "$lt{'youm'}\\n";
 6521:     }
 6522: 
 6523:     if (srchtype== 'begins') {
 6524:         if (srchterm.length < 2) {
 6525:             checkok = 0;
 6526:             msg += "$lt{'thte'}\\n";
 6527:         }
 6528:     }
 6529: 
 6530:     if (srchtype== 'contains') {
 6531:         if (srchterm.length < 3) {
 6532:             checkok = 0;
 6533:             msg += "$lt{'thet'}\\n";
 6534:         }
 6535:     }
 6536:     if (srchin == 'instd') {
 6537:         if (srchdomain == '') {
 6538:             checkok = 0;
 6539:             msg += "$lt{'yomc'}\\n";
 6540:         }
 6541:     }
 6542:     if (srchin == 'dom') {
 6543:         if (srchdomain == '') {
 6544:             checkok = 0;
 6545:             msg += "$lt{'ymcd'}\\n";
 6546:         }
 6547:     }
 6548:     if (srchby == 'lastfirst') {
 6549:         if (srchterm.indexOf(",") == -1) {
 6550:             checkok = 0;
 6551:             msg += "$lt{'whus'}\\n";
 6552:         }
 6553:         if (srchterm.indexOf(",") == srchterm.length -1) {
 6554:             checkok = 0;
 6555:             msg += "$lt{'whse'}\\n";
 6556:         }
 6557:     }
 6558:     if (checkok == 0) {
 6559:         alert("$lt{'thfo'}\\n"+msg);
 6560:         return;
 6561:     }
 6562:     if (checkok == 1) {
 6563:         callingForm.submit();
 6564:     }
 6565: }
 6566: 
 6567: $newuserscript
 6568: 
 6569: </script>
 6570: 
 6571: $new_user_create
 6572: 
 6573: <table>
 6574:  <tr>
 6575:   <td>$lt{'doma'}:</td>
 6576:   <td>$domform</td>
 6577:   </td>
 6578:  </tr>
 6579:  <tr>
 6580:   <td>$lt{'usr'}:</td>
 6581:   <td>$srchbysel
 6582:       $srchtypesel 
 6583:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 6584:       $srchinsel 
 6585:   </td>
 6586:  </tr>
 6587: </table>
 6588: <br />
 6589: END_BLOCK
 6590: 
 6591:     return $output;
 6592: }
 6593: 
 6594: sub user_rule_check {
 6595:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 6596:     my $response;
 6597:     if (ref($usershash) eq 'HASH') {
 6598:         foreach my $user (keys(%{$usershash})) {
 6599:             my ($uname,$udom) = split(/:/,$user);
 6600:             next if ($udom eq '' || $uname eq '');
 6601:             my ($id,$newuser);
 6602:             if (ref($usershash->{$user}) eq 'HASH') {
 6603:                 $newuser = $usershash->{$user}->{'newuser'};
 6604:                 $id = $usershash->{$user}->{'id'};
 6605:             }
 6606:             my $inst_response;
 6607:             if (ref($checks) eq 'HASH') {
 6608:                 if (defined($checks->{'username'})) {
 6609:                     ($inst_response,%{$inst_results->{$user}}) = 
 6610:                         &Apache::lonnet::get_instuser($udom,$uname);
 6611:                 } elsif (defined($checks->{'id'})) {
 6612:                     ($inst_response,%{$inst_results->{$user}}) =
 6613:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 6614:                 }
 6615:             } else {
 6616:                 ($inst_response,%{$inst_results->{$user}}) =
 6617:                     &Apache::lonnet::get_instuser($udom,$uname);
 6618:                 return;
 6619:             }
 6620:             if (!$got_rules->{$udom}) {
 6621:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 6622:                                                   ['usercreation'],$udom);
 6623:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6624:                     foreach my $item ('username','id') {
 6625:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 6626:                             $$curr_rules{$udom}{$item} = 
 6627:                                 $domconfig{'usercreation'}{$item.'_rule'};
 6628:                         }
 6629:                     }
 6630:                 }
 6631:                 $got_rules->{$udom} = 1;  
 6632:             }
 6633:             foreach my $item (keys(%{$checks})) {
 6634:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 6635:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 6636:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 6637:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 6638:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 6639:                                 if ($rule_check{$rule}) {
 6640:                                     $$rulematch{$user}{$item} = $rule;
 6641:                                     if ($inst_response eq 'ok') {
 6642:                                         if (ref($inst_results) eq 'HASH') {
 6643:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 6644:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 6645:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 6646:                                                 }
 6647:                                             }
 6648:                                         }
 6649:                                     }
 6650:                                     last;
 6651:                                 }
 6652:                             }
 6653:                         }
 6654:                     }
 6655:                 }
 6656:             }
 6657:         }
 6658:     }
 6659:     return;
 6660: }
 6661: 
 6662: sub user_rule_formats {
 6663:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 6664:     my %text = ( 
 6665:                  'username' => 'Usernames',
 6666:                  'id'       => 'IDs',
 6667:                );
 6668:     my $output;
 6669:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 6670:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 6671:         if (@{$ruleorder} > 0) {
 6672:             $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>';
 6673:             foreach my $rule (@{$ruleorder}) {
 6674:                 if (ref($curr_rules) eq 'ARRAY') {
 6675:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 6676:                         if (ref($rules->{$rule}) eq 'HASH') {
 6677:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 6678:                                         $rules->{$rule}{'desc'}.'</li>';
 6679:                         }
 6680:                     }
 6681:                 }
 6682:             }
 6683:             $output .= '</ul>';
 6684:         }
 6685:     }
 6686:     return $output;
 6687: }
 6688: 
 6689: sub instrule_disallow_msg {
 6690:     my ($checkitem,$domdesc,$count,$mode) = @_;
 6691:     my $response;
 6692:     my %text = (
 6693:                   item   => 'username',
 6694:                   items  => 'usernames',
 6695:                   match  => 'matches',
 6696:                   do     => 'does',
 6697:                   action => 'a username',
 6698:                   one    => 'one',
 6699:                );
 6700:     if ($count > 1) {
 6701:         $text{'item'} = 'usernames';
 6702:         $text{'match'} ='match';
 6703:         $text{'do'} = 'do';
 6704:         $text{'action'} = 'usernames',
 6705:         $text{'one'} = 'ones';
 6706:     }
 6707:     if ($checkitem eq 'id') {
 6708:         $text{'items'} = 'IDs';
 6709:         $text{'item'} = 'ID';
 6710:         $text{'action'} = 'an ID';
 6711:         if ($count > 1) {
 6712:             $text{'item'} = 'IDs';
 6713:             $text{'action'} = 'IDs';
 6714:         }
 6715:     }
 6716:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for <span class=\"LC_cusr_emph\">[_1]</span>, but the $text{'item'} $text{'do'} not exist in the institutional directory.",$domdesc).'<br />';
 6717:     if ($mode eq 'upload') {
 6718:         if ($checkitem eq 'username') {
 6719:             $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'}.");
 6720:         } elsif ($checkitem eq 'id') {
 6721:             $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 ID/Student Number field.");
 6722:         }
 6723:     } else {
 6724:         if ($checkitem eq 'username') {
 6725:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 6726:         } elsif ($checkitem eq 'id') {
 6727:             $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.");
 6728:         }
 6729:     }
 6730:     return $response;
 6731: }
 6732: 
 6733: sub personal_data_fieldtitles {
 6734:     my %fieldtitles = &Apache::lonlocal::texthash (
 6735:                         id => 'Student/Employee ID',
 6736:                         permanentemail => 'E-mail address',
 6737:                         lastname => 'Last Name',
 6738:                         firstname => 'First Name',
 6739:                         middlename => 'Middle Name',
 6740:                         generation => 'Generation',
 6741:                         gen => 'Generation',
 6742:                    );
 6743:     return %fieldtitles;
 6744: }
 6745: 
 6746: sub sorted_inst_types {
 6747:     my ($dom) = @_;
 6748:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 6749:     my $othertitle = &mt('All users');
 6750:     if ($env{'request.course.id'}) {
 6751:         $othertitle  = 'any';
 6752:     }
 6753:     my @types;
 6754:     if (ref($order) eq 'ARRAY') {
 6755:         @types = @{$order};
 6756:     }
 6757:     if (@types == 0) {
 6758:         if (ref($usertypes) eq 'HASH') {
 6759:             @types = sort(keys(%{$usertypes}));
 6760:         }
 6761:     }
 6762:     if (keys(%{$usertypes}) > 0) {
 6763:         $othertitle = &mt('Other users');
 6764:         if ($env{'request.course.id'}) {
 6765:             $othertitle = 'other';
 6766:         }
 6767:     }
 6768:     return ($othertitle,$usertypes,\@types);
 6769: }
 6770: 
 6771: sub get_institutional_codes {
 6772:     my ($settings,$allcourses,$LC_code) = @_;
 6773: # Get complete list of course sections to update
 6774:     my @currsections = ();
 6775:     my @currxlists = ();
 6776:     my $coursecode = $$settings{'internal.coursecode'};
 6777: 
 6778:     if ($$settings{'internal.sectionnums'} ne '') {
 6779:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 6780:     }
 6781: 
 6782:     if ($$settings{'internal.crosslistings'} ne '') {
 6783:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 6784:     }
 6785: 
 6786:     if (@currxlists > 0) {
 6787:         foreach (@currxlists) {
 6788:             if (m/^([^:]+):(\w*)$/) {
 6789:                 unless (grep/^$1$/,@{$allcourses}) {
 6790:                     push @{$allcourses},$1;
 6791:                     $$LC_code{$1} = $2;
 6792:                 }
 6793:             }
 6794:         }
 6795:     }
 6796:  
 6797:     if (@currsections > 0) {
 6798:         foreach (@currsections) {
 6799:             if (m/^(\w+):(\w*)$/) {
 6800:                 my $sec = $coursecode.$1;
 6801:                 my $lc_sec = $2;
 6802:                 unless (grep/^$sec$/,@{$allcourses}) {
 6803:                     push @{$allcourses},$sec;
 6804:                     $$LC_code{$sec} = $lc_sec;
 6805:                 }
 6806:             }
 6807:         }
 6808:     }
 6809:     return;
 6810: }
 6811: 
 6812: =pod
 6813: 
 6814: =back
 6815: 
 6816: =head1 HTTP Helpers
 6817: 
 6818: =over 4
 6819: 
 6820: =item * &get_unprocessed_cgi($query,$possible_names)
 6821: 
 6822: Modify the %env hash to contain unprocessed CGI form parameters held in
 6823: $query.  The parameters listed in $possible_names (an array reference),
 6824: will be set in $env{'form.name'} if they do not already exist.
 6825: 
 6826: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 6827: $possible_names is an ref to an array of form element names.  As an example:
 6828: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 6829: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 6830: 
 6831: =cut
 6832: 
 6833: sub get_unprocessed_cgi {
 6834:   my ($query,$possible_names)= @_;
 6835:   # $Apache::lonxml::debug=1;
 6836:   foreach my $pair (split(/&/,$query)) {
 6837:     my ($name, $value) = split(/=/,$pair);
 6838:     $name = &unescape($name);
 6839:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 6840:       $value =~ tr/+/ /;
 6841:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 6842:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 6843:     }
 6844:   }
 6845: }
 6846: 
 6847: =pod
 6848: 
 6849: =item * &cacheheader() 
 6850: 
 6851: returns cache-controlling header code
 6852: 
 6853: =cut
 6854: 
 6855: sub cacheheader {
 6856:     unless ($env{'request.method'} eq 'GET') { return ''; }
 6857:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 6858:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 6859:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 6860:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 6861:     return $output;
 6862: }
 6863: 
 6864: =pod
 6865: 
 6866: =item * &no_cache($r) 
 6867: 
 6868: specifies header code to not have cache
 6869: 
 6870: =cut
 6871: 
 6872: sub no_cache {
 6873:     my ($r) = @_;
 6874:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 6875: 	$env{'request.method'} ne 'GET') { return ''; }
 6876:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 6877:     $r->no_cache(1);
 6878:     $r->header_out("Expires" => $date);
 6879:     $r->header_out("Pragma" => "no-cache");
 6880: }
 6881: 
 6882: sub content_type {
 6883:     my ($r,$type,$charset) = @_;
 6884:     if ($r) {
 6885: 	#  Note that printout.pl calls this with undef for $r.
 6886: 	&no_cache($r);
 6887:     }
 6888:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 6889:     unless ($charset) {
 6890: 	$charset=&Apache::lonlocal::current_encoding;
 6891:     }
 6892:     if ($charset) { $type.='; charset='.$charset; }
 6893:     if ($r) {
 6894: 	$r->content_type($type);
 6895:     } else {
 6896: 	print("Content-type: $type\n\n");
 6897:     }
 6898: }
 6899: 
 6900: =pod
 6901: 
 6902: =item * &add_to_env($name,$value) 
 6903: 
 6904: adds $name to the %env hash with value
 6905: $value, if $name already exists, the entry is converted to an array
 6906: reference and $value is added to the array.
 6907: 
 6908: =cut
 6909: 
 6910: sub add_to_env {
 6911:   my ($name,$value)=@_;
 6912:   if (defined($env{$name})) {
 6913:     if (ref($env{$name})) {
 6914:       #already have multiple values
 6915:       push(@{ $env{$name} },$value);
 6916:     } else {
 6917:       #first time seeing multiple values, convert hash entry to an arrayref
 6918:       my $first=$env{$name};
 6919:       undef($env{$name});
 6920:       push(@{ $env{$name} },$first,$value);
 6921:     }
 6922:   } else {
 6923:     $env{$name}=$value;
 6924:   }
 6925: }
 6926: 
 6927: =pod
 6928: 
 6929: =item * &get_env_multiple($name) 
 6930: 
 6931: gets $name from the %env hash, it seemlessly handles the cases where multiple
 6932: values may be defined and end up as an array ref.
 6933: 
 6934: returns an array of values
 6935: 
 6936: =cut
 6937: 
 6938: sub get_env_multiple {
 6939:     my ($name) = @_;
 6940:     my @values;
 6941:     if (defined($env{$name})) {
 6942:         # exists is it an array
 6943:         if (ref($env{$name})) {
 6944:             @values=@{ $env{$name} };
 6945:         } else {
 6946:             $values[0]=$env{$name};
 6947:         }
 6948:     }
 6949:     return(@values);
 6950: }
 6951: 
 6952: 
 6953: =pod
 6954: 
 6955: =back
 6956: 
 6957: =head1 CSV Upload/Handling functions
 6958: 
 6959: =over 4
 6960: 
 6961: =item * &upfile_store($r)
 6962: 
 6963: Store uploaded file, $r should be the HTTP Request object,
 6964: needs $env{'form.upfile'}
 6965: returns $datatoken to be put into hidden field
 6966: 
 6967: =cut
 6968: 
 6969: sub upfile_store {
 6970:     my $r=shift;
 6971:     $env{'form.upfile'}=~s/\r/\n/gs;
 6972:     $env{'form.upfile'}=~s/\f/\n/gs;
 6973:     $env{'form.upfile'}=~s/\n+/\n/gs;
 6974:     $env{'form.upfile'}=~s/\n+$//gs;
 6975: 
 6976:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 6977: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 6978:     {
 6979:         my $datafile = $r->dir_config('lonDaemons').
 6980:                            '/tmp/'.$datatoken.'.tmp';
 6981:         if ( open(my $fh,">$datafile") ) {
 6982:             print $fh $env{'form.upfile'};
 6983:             close($fh);
 6984:         }
 6985:     }
 6986:     return $datatoken;
 6987: }
 6988: 
 6989: =pod
 6990: 
 6991: =item * &load_tmp_file($r)
 6992: 
 6993: Load uploaded file from tmp, $r should be the HTTP Request object,
 6994: needs $env{'form.datatoken'},
 6995: sets $env{'form.upfile'} to the contents of the file
 6996: 
 6997: =cut
 6998: 
 6999: sub load_tmp_file {
 7000:     my $r=shift;
 7001:     my @studentdata=();
 7002:     {
 7003:         my $studentfile = $r->dir_config('lonDaemons').
 7004:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7005:         if ( open(my $fh,"<$studentfile") ) {
 7006:             @studentdata=<$fh>;
 7007:             close($fh);
 7008:         }
 7009:     }
 7010:     $env{'form.upfile'}=join('',@studentdata);
 7011: }
 7012: 
 7013: =pod
 7014: 
 7015: =item * &upfile_record_sep()
 7016: 
 7017: Separate uploaded file into records
 7018: returns array of records,
 7019: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7020: 
 7021: =cut
 7022: 
 7023: sub upfile_record_sep {
 7024:     if ($env{'form.upfiletype'} eq 'xml') {
 7025:     } else {
 7026: 	my @records;
 7027: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7028: 	    if ($line=~/^\s*$/) { next; }
 7029: 	    push(@records,$line);
 7030: 	}
 7031: 	return @records;
 7032:     }
 7033: }
 7034: 
 7035: =pod
 7036: 
 7037: =item * &record_sep($record)
 7038: 
 7039: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7040: 
 7041: =cut
 7042: 
 7043: sub takeleft {
 7044:     my $index=shift;
 7045:     return substr('0000'.$index,-4,4);
 7046: }
 7047: 
 7048: sub record_sep {
 7049:     my $record=shift;
 7050:     my %components=();
 7051:     if ($env{'form.upfiletype'} eq 'xml') {
 7052:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7053:         my $i=0;
 7054:         foreach my $field (split(/\s+/,$record)) {
 7055:             $field=~s/^(\"|\')//;
 7056:             $field=~s/(\"|\')$//;
 7057:             $components{&takeleft($i)}=$field;
 7058:             $i++;
 7059:         }
 7060:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7061:         my $i=0;
 7062:         foreach my $field (split(/\t/,$record)) {
 7063:             $field=~s/^(\"|\')//;
 7064:             $field=~s/(\"|\')$//;
 7065:             $components{&takeleft($i)}=$field;
 7066:             $i++;
 7067:         }
 7068:     } else {
 7069:         my $separator=',';
 7070:         if ($env{'form.upfiletype'} eq 'semisv') {
 7071:             $separator=';';
 7072:         }
 7073:         my $i=0;
 7074: # the character we are looking for to indicate the end of a quote or a record 
 7075:         my $looking_for=$separator;
 7076: # do not add the characters to the fields
 7077:         my $ignore=0;
 7078: # we just encountered a separator (or the beginning of the record)
 7079:         my $just_found_separator=1;
 7080: # store the field we are working on here
 7081:         my $field='';
 7082: # work our way through all characters in record
 7083:         foreach my $character ($record=~/(.)/g) {
 7084:             if ($character eq $looking_for) {
 7085:                if ($character ne $separator) {
 7086: # Found the end of a quote, again looking for separator
 7087:                   $looking_for=$separator;
 7088:                   $ignore=1;
 7089:                } else {
 7090: # Found a separator, store away what we got
 7091:                   $components{&takeleft($i)}=$field;
 7092: 	          $i++;
 7093:                   $just_found_separator=1;
 7094:                   $ignore=0;
 7095:                   $field='';
 7096:                }
 7097:                next;
 7098:             }
 7099: # single or double quotation marks after a separator indicate beginning of a quote
 7100: # we are now looking for the end of the quote and need to ignore separators
 7101:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7102:                $looking_for=$character;
 7103:                next;
 7104:             }
 7105: # ignore would be true after we reached the end of a quote
 7106:             if ($ignore) { next; }
 7107:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7108:             $field.=$character;
 7109:             $just_found_separator=0; 
 7110:         }
 7111: # catch the very last entry, since we never encountered the separator
 7112:         $components{&takeleft($i)}=$field;
 7113:     }
 7114:     return %components;
 7115: }
 7116: 
 7117: ######################################################
 7118: ######################################################
 7119: 
 7120: =pod
 7121: 
 7122: =item * &upfile_select_html()
 7123: 
 7124: Return HTML code to select a file from the users machine and specify 
 7125: the file type.
 7126: 
 7127: =cut
 7128: 
 7129: ######################################################
 7130: ######################################################
 7131: sub upfile_select_html {
 7132:     my %Types = (
 7133:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7134:                  semisv => &mt('Semicolon separated values'),
 7135:                  space => &mt('Space separated'),
 7136:                  tab   => &mt('Tabulator separated'),
 7137: #                 xml   => &mt('HTML/XML'),
 7138:                  );
 7139:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7140:         '<br />Type: <select name="upfiletype">';
 7141:     foreach my $type (sort(keys(%Types))) {
 7142:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7143:     }
 7144:     $Str .= "</select>\n";
 7145:     return $Str;
 7146: }
 7147: 
 7148: sub get_samples {
 7149:     my ($records,$toget) = @_;
 7150:     my @samples=({});
 7151:     my $got=0;
 7152:     foreach my $rec (@$records) {
 7153: 	my %temp = &record_sep($rec);
 7154: 	if (! grep(/\S/, values(%temp))) { next; }
 7155: 	if (%temp) {
 7156: 	    $samples[$got]=\%temp;
 7157: 	    $got++;
 7158: 	    if ($got == $toget) { last; }
 7159: 	}
 7160:     }
 7161:     return \@samples;
 7162: }
 7163: 
 7164: ######################################################
 7165: ######################################################
 7166: 
 7167: =pod
 7168: 
 7169: =item * &csv_print_samples($r,$records)
 7170: 
 7171: Prints a table of sample values from each column uploaded $r is an
 7172: Apache Request ref, $records is an arrayref from
 7173: &Apache::loncommon::upfile_record_sep
 7174: 
 7175: =cut
 7176: 
 7177: ######################################################
 7178: ######################################################
 7179: sub csv_print_samples {
 7180:     my ($r,$records) = @_;
 7181:     my $samples = &get_samples($records,3);
 7182: 
 7183:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 7184:               &start_data_table_header_row());
 7185:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 7186:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 7187:     $r->print(&end_data_table_header_row());
 7188:     foreach my $hash (@$samples) {
 7189: 	$r->print(&start_data_table_row());
 7190: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7191: 	    $r->print('<td>');
 7192: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 7193: 	    $r->print('</td>');
 7194: 	}
 7195: 	$r->print(&end_data_table_row());
 7196:     }
 7197:     $r->print(&end_data_table().'<br />'."\n");
 7198: }
 7199: 
 7200: ######################################################
 7201: ######################################################
 7202: 
 7203: =pod
 7204: 
 7205: =item * &csv_print_select_table($r,$records,$d)
 7206: 
 7207: Prints a table to create associations between values and table columns.
 7208: 
 7209: $r is an Apache Request ref,
 7210: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7211: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 7212: 
 7213: =cut
 7214: 
 7215: ######################################################
 7216: ######################################################
 7217: sub csv_print_select_table {
 7218:     my ($r,$records,$d) = @_;
 7219:     my $i=0;
 7220:     my $samples = &get_samples($records,1);
 7221:     $r->print(&mt('Associate columns with student attributes.')."\n".
 7222: 	      &start_data_table().&start_data_table_header_row().
 7223:               '<th>'.&mt('Attribute').'</th>'.
 7224:               '<th>'.&mt('Column').'</th>'.
 7225:               &end_data_table_header_row()."\n");
 7226:     foreach my $array_ref (@$d) {
 7227: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 7228: 	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
 7229: 
 7230: 	$r->print('<td><select name=f'.$i.
 7231: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7232: 	$r->print('<option value="none"></option>');
 7233: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7234: 	    $r->print('<option value="'.$sample.'"'.
 7235:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 7236:                       '>Column '.($sample+1).'</option>');
 7237: 	}
 7238: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 7239: 	$i++;
 7240:     }
 7241:     $r->print(&end_data_table());
 7242:     $i--;
 7243:     return $i;
 7244: }
 7245: 
 7246: ######################################################
 7247: ######################################################
 7248: 
 7249: =pod
 7250: 
 7251: =item * &csv_samples_select_table($r,$records,$d)
 7252: 
 7253: Prints a table of sample values from the upload and can make associate samples to internal names.
 7254: 
 7255: $r is an Apache Request ref,
 7256: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7257: $d is an array of 2 element arrays (internal name, displayed name)
 7258: 
 7259: =cut
 7260: 
 7261: ######################################################
 7262: ######################################################
 7263: sub csv_samples_select_table {
 7264:     my ($r,$records,$d) = @_;
 7265:     my $i=0;
 7266:     #
 7267:     my $samples = &get_samples($records,3);
 7268:     $r->print(&start_data_table().
 7269:               &start_data_table_header_row().'<th>'.
 7270:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 7271:               &end_data_table_header_row());
 7272: 
 7273:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 7274: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 7275: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7276: 	foreach my $option (@$d) {
 7277: 	    my ($value,$display,$defaultcol)=@{ $option };
 7278: 	    $r->print('<option value="'.$value.'"'.
 7279:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 7280:                       $display.'</option>');
 7281: 	}
 7282: 	$r->print('</select></td><td>');
 7283: 	foreach my $line (0..2) {
 7284: 	    if (defined($samples->[$line]{$key})) { 
 7285: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 7286: 	    }
 7287: 	}
 7288: 	$r->print('</td>'.&end_data_table_row());
 7289: 	$i++;
 7290:     }
 7291:     $r->print(&end_data_table());
 7292:     $i--;
 7293:     return($i);
 7294: }
 7295: 
 7296: ######################################################
 7297: ######################################################
 7298: 
 7299: =pod
 7300: 
 7301: =item * &clean_excel_name($name)
 7302: 
 7303: Returns a replacement for $name which does not contain any illegal characters.
 7304: 
 7305: =cut
 7306: 
 7307: ######################################################
 7308: ######################################################
 7309: sub clean_excel_name {
 7310:     my ($name) = @_;
 7311:     $name =~ s/[:\*\?\/\\]//g;
 7312:     if (length($name) > 31) {
 7313:         $name = substr($name,0,31);
 7314:     }
 7315:     return $name;
 7316: }
 7317: 
 7318: =pod
 7319: 
 7320: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 7321: 
 7322: Returns either 1 or undef
 7323: 
 7324: 1 if the part is to be hidden, undef if it is to be shown
 7325: 
 7326: Arguments are:
 7327: 
 7328: $id the id of the part to be checked
 7329: $symb, optional the symb of the resource to check
 7330: $udom, optional the domain of the user to check for
 7331: $uname, optional the username of the user to check for
 7332: 
 7333: =cut
 7334: 
 7335: sub check_if_partid_hidden {
 7336:     my ($id,$symb,$udom,$uname) = @_;
 7337:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 7338: 					 $symb,$udom,$uname);
 7339:     my $truth=1;
 7340:     #if the string starts with !, then the list is the list to show not hide
 7341:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 7342:     my @hiddenlist=split(/,/,$hiddenparts);
 7343:     foreach my $checkid (@hiddenlist) {
 7344: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 7345:     }
 7346:     return !$truth;
 7347: }
 7348: 
 7349: 
 7350: ############################################################
 7351: ############################################################
 7352: 
 7353: =pod
 7354: 
 7355: =back 
 7356: 
 7357: =head1 cgi-bin script and graphing routines
 7358: 
 7359: =over 4
 7360: 
 7361: =item * &get_cgi_id()
 7362: 
 7363: Inputs: none
 7364: 
 7365: Returns an id which can be used to pass environment variables
 7366: to various cgi-bin scripts.  These environment variables will
 7367: be removed from the users environment after a given time by
 7368: the routine &Apache::lonnet::transfer_profile_to_env.
 7369: 
 7370: =cut
 7371: 
 7372: ############################################################
 7373: ############################################################
 7374: my $uniq=0;
 7375: sub get_cgi_id {
 7376:     $uniq=($uniq+1)%100000;
 7377:     return (time.'_'.$$.'_'.$uniq);
 7378: }
 7379: 
 7380: ############################################################
 7381: ############################################################
 7382: 
 7383: =pod
 7384: 
 7385: =item * &DrawBarGraph()
 7386: 
 7387: Facilitates the plotting of data in a (stacked) bar graph.
 7388: Puts plot definition data into the users environment in order for 
 7389: graph.png to plot it.  Returns an <img> tag for the plot.
 7390: The bars on the plot are labeled '1','2',...,'n'.
 7391: 
 7392: Inputs:
 7393: 
 7394: =over 4
 7395: 
 7396: =item $Title: string, the title of the plot
 7397: 
 7398: =item $xlabel: string, text describing the X-axis of the plot
 7399: 
 7400: =item $ylabel: string, text describing the Y-axis of the plot
 7401: 
 7402: =item $Max: scalar, the maximum Y value to use in the plot
 7403: If $Max is < any data point, the graph will not be rendered.
 7404: 
 7405: =item $colors: array ref holding the colors to be used for the data sets when
 7406: they are plotted.  If undefined, default values will be used.
 7407: 
 7408: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 7409: 
 7410: =item @Values: An array of array references.  Each array reference holds data
 7411: to be plotted in a stacked bar chart.
 7412: 
 7413: =item If the final element of @Values is a hash reference the key/value
 7414: pairs will be added to the graph definition.
 7415: 
 7416: =back
 7417: 
 7418: Returns:
 7419: 
 7420: An <img> tag which references graph.png and the appropriate identifying
 7421: information for the plot.
 7422: 
 7423: =cut
 7424: 
 7425: ############################################################
 7426: ############################################################
 7427: sub DrawBarGraph {
 7428:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 7429:     #
 7430:     if (! defined($colors)) {
 7431:         $colors = ['#33ff00', 
 7432:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 7433:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 7434:                   ]; 
 7435:     }
 7436:     my $extra_settings = {};
 7437:     if (ref($Values[-1]) eq 'HASH') {
 7438:         $extra_settings = pop(@Values);
 7439:     }
 7440:     #
 7441:     my $identifier = &get_cgi_id();
 7442:     my $id = 'cgi.'.$identifier;        
 7443:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 7444:         return '';
 7445:     }
 7446:     #
 7447:     my @Labels;
 7448:     if (defined($labels)) {
 7449:         @Labels = @$labels;
 7450:     } else {
 7451:         for (my $i=0;$i<@{$Values[0]};$i++) {
 7452:             push (@Labels,$i+1);
 7453:         }
 7454:     }
 7455:     #
 7456:     my $NumBars = scalar(@{$Values[0]});
 7457:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 7458:     my %ValuesHash;
 7459:     my $NumSets=1;
 7460:     foreach my $array (@Values) {
 7461:         next if (! ref($array));
 7462:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 7463:             join(',',@$array);
 7464:     }
 7465:     #
 7466:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 7467:     if ($NumBars < 3) {
 7468:         $width = 120+$NumBars*32;
 7469:         $xskip = 1;
 7470:         $bar_width = 30;
 7471:     } elsif ($NumBars < 5) {
 7472:         $width = 120+$NumBars*20;
 7473:         $xskip = 1;
 7474:         $bar_width = 20;
 7475:     } elsif ($NumBars < 10) {
 7476:         $width = 120+$NumBars*15;
 7477:         $xskip = 1;
 7478:         $bar_width = 15;
 7479:     } elsif ($NumBars <= 25) {
 7480:         $width = 120+$NumBars*11;
 7481:         $xskip = 5;
 7482:         $bar_width = 8;
 7483:     } elsif ($NumBars <= 50) {
 7484:         $width = 120+$NumBars*8;
 7485:         $xskip = 5;
 7486:         $bar_width = 4;
 7487:     } else {
 7488:         $width = 120+$NumBars*8;
 7489:         $xskip = 5;
 7490:         $bar_width = 4;
 7491:     }
 7492:     #
 7493:     $Max = 1 if ($Max < 1);
 7494:     if ( int($Max) < $Max ) {
 7495:         $Max++;
 7496:         $Max = int($Max);
 7497:     }
 7498:     $Title  = '' if (! defined($Title));
 7499:     $xlabel = '' if (! defined($xlabel));
 7500:     $ylabel = '' if (! defined($ylabel));
 7501:     $ValuesHash{$id.'.title'}    = &escape($Title);
 7502:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 7503:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 7504:     $ValuesHash{$id.'.y_max_value'} = $Max;
 7505:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 7506:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 7507:     $ValuesHash{$id.'.PlotType'} = 'bar';
 7508:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7509:     $ValuesHash{$id.'.height'}   = $height;
 7510:     $ValuesHash{$id.'.width'}    = $width;
 7511:     $ValuesHash{$id.'.xskip'}    = $xskip;
 7512:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 7513:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 7514:     #
 7515:     # Deal with other parameters
 7516:     while (my ($key,$value) = each(%$extra_settings)) {
 7517:         $ValuesHash{$id.'.'.$key} = $value;
 7518:     }
 7519:     #
 7520:     &Apache::lonnet::appenv(\%ValuesHash);
 7521:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7522: }
 7523: 
 7524: ############################################################
 7525: ############################################################
 7526: 
 7527: =pod
 7528: 
 7529: =item * &DrawXYGraph()
 7530: 
 7531: Facilitates the plotting of data in an XY graph.
 7532: Puts plot definition data into the users environment in order for 
 7533: graph.png to plot it.  Returns an <img> tag for the plot.
 7534: 
 7535: Inputs:
 7536: 
 7537: =over 4
 7538: 
 7539: =item $Title: string, the title of the plot
 7540: 
 7541: =item $xlabel: string, text describing the X-axis of the plot
 7542: 
 7543: =item $ylabel: string, text describing the Y-axis of the plot
 7544: 
 7545: =item $Max: scalar, the maximum Y value to use in the plot
 7546: If $Max is < any data point, the graph will not be rendered.
 7547: 
 7548: =item $colors: Array ref containing the hex color codes for the data to be 
 7549: plotted in.  If undefined, default values will be used.
 7550: 
 7551: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7552: 
 7553: =item $Ydata: Array ref containing Array refs.  
 7554: Each of the contained arrays will be plotted as a separate curve.
 7555: 
 7556: =item %Values: hash indicating or overriding any default values which are 
 7557: passed to graph.png.  
 7558: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7559: 
 7560: =back
 7561: 
 7562: Returns:
 7563: 
 7564: An <img> tag which references graph.png and the appropriate identifying
 7565: information for the plot.
 7566: 
 7567: =cut
 7568: 
 7569: ############################################################
 7570: ############################################################
 7571: sub DrawXYGraph {
 7572:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 7573:     #
 7574:     # Create the identifier for the graph
 7575:     my $identifier = &get_cgi_id();
 7576:     my $id = 'cgi.'.$identifier;
 7577:     #
 7578:     $Title  = '' if (! defined($Title));
 7579:     $xlabel = '' if (! defined($xlabel));
 7580:     $ylabel = '' if (! defined($ylabel));
 7581:     my %ValuesHash = 
 7582:         (
 7583:          $id.'.title'  => &escape($Title),
 7584:          $id.'.xlabel' => &escape($xlabel),
 7585:          $id.'.ylabel' => &escape($ylabel),
 7586:          $id.'.y_max_value'=> $Max,
 7587:          $id.'.labels'     => join(',',@$Xlabels),
 7588:          $id.'.PlotType'   => 'XY',
 7589:          );
 7590:     #
 7591:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 7592:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7593:     }
 7594:     #
 7595:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 7596:         return '';
 7597:     }
 7598:     my $NumSets=1;
 7599:     foreach my $array (@{$Ydata}){
 7600:         next if (! ref($array));
 7601:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 7602:     }
 7603:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 7604:     #
 7605:     # Deal with other parameters
 7606:     while (my ($key,$value) = each(%Values)) {
 7607:         $ValuesHash{$id.'.'.$key} = $value;
 7608:     }
 7609:     #
 7610:     &Apache::lonnet::appenv(\%ValuesHash);
 7611:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7612: }
 7613: 
 7614: ############################################################
 7615: ############################################################
 7616: 
 7617: =pod
 7618: 
 7619: =item * &DrawXYYGraph()
 7620: 
 7621: Facilitates the plotting of data in an XY graph with two Y axes.
 7622: Puts plot definition data into the users environment in order for 
 7623: graph.png to plot it.  Returns an <img> tag for the plot.
 7624: 
 7625: Inputs:
 7626: 
 7627: =over 4
 7628: 
 7629: =item $Title: string, the title of the plot
 7630: 
 7631: =item $xlabel: string, text describing the X-axis of the plot
 7632: 
 7633: =item $ylabel: string, text describing the Y-axis of the plot
 7634: 
 7635: =item $colors: Array ref containing the hex color codes for the data to be 
 7636: plotted in.  If undefined, default values will be used.
 7637: 
 7638: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7639: 
 7640: =item $Ydata1: The first data set
 7641: 
 7642: =item $Min1: The minimum value of the left Y-axis
 7643: 
 7644: =item $Max1: The maximum value of the left Y-axis
 7645: 
 7646: =item $Ydata2: The second data set
 7647: 
 7648: =item $Min2: The minimum value of the right Y-axis
 7649: 
 7650: =item $Max2: The maximum value of the left Y-axis
 7651: 
 7652: =item %Values: hash indicating or overriding any default values which are 
 7653: passed to graph.png.  
 7654: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7655: 
 7656: =back
 7657: 
 7658: Returns:
 7659: 
 7660: An <img> tag which references graph.png and the appropriate identifying
 7661: information for the plot.
 7662: 
 7663: =cut
 7664: 
 7665: ############################################################
 7666: ############################################################
 7667: sub DrawXYYGraph {
 7668:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 7669:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 7670:     #
 7671:     # Create the identifier for the graph
 7672:     my $identifier = &get_cgi_id();
 7673:     my $id = 'cgi.'.$identifier;
 7674:     #
 7675:     $Title  = '' if (! defined($Title));
 7676:     $xlabel = '' if (! defined($xlabel));
 7677:     $ylabel = '' if (! defined($ylabel));
 7678:     my %ValuesHash = 
 7679:         (
 7680:          $id.'.title'  => &escape($Title),
 7681:          $id.'.xlabel' => &escape($xlabel),
 7682:          $id.'.ylabel' => &escape($ylabel),
 7683:          $id.'.labels' => join(',',@$Xlabels),
 7684:          $id.'.PlotType' => 'XY',
 7685:          $id.'.NumSets' => 2,
 7686:          $id.'.two_axes' => 1,
 7687:          $id.'.y1_max_value' => $Max1,
 7688:          $id.'.y1_min_value' => $Min1,
 7689:          $id.'.y2_max_value' => $Max2,
 7690:          $id.'.y2_min_value' => $Min2,
 7691:          );
 7692:     #
 7693:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 7694:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7695:     }
 7696:     #
 7697:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 7698:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 7699:         return '';
 7700:     }
 7701:     my $NumSets=1;
 7702:     foreach my $array ($Ydata1,$Ydata2){
 7703:         next if (! ref($array));
 7704:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 7705:     }
 7706:     #
 7707:     # Deal with other parameters
 7708:     while (my ($key,$value) = each(%Values)) {
 7709:         $ValuesHash{$id.'.'.$key} = $value;
 7710:     }
 7711:     #
 7712:     &Apache::lonnet::appenv(\%ValuesHash);
 7713:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7714: }
 7715: 
 7716: ############################################################
 7717: ############################################################
 7718: 
 7719: =pod
 7720: 
 7721: =back 
 7722: 
 7723: =head1 Statistics helper routines?  
 7724: 
 7725: Bad place for them but what the hell.
 7726: 
 7727: =over 4
 7728: 
 7729: =item * &chartlink()
 7730: 
 7731: Returns a link to the chart for a specific student.  
 7732: 
 7733: Inputs:
 7734: 
 7735: =over 4
 7736: 
 7737: =item $linktext: The text of the link
 7738: 
 7739: =item $sname: The students username
 7740: 
 7741: =item $sdomain: The students domain
 7742: 
 7743: =back
 7744: 
 7745: =back
 7746: 
 7747: =cut
 7748: 
 7749: ############################################################
 7750: ############################################################
 7751: sub chartlink {
 7752:     my ($linktext, $sname, $sdomain) = @_;
 7753:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 7754:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 7755:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 7756:        '">'.$linktext.'</a>';
 7757: }
 7758: 
 7759: #######################################################
 7760: #######################################################
 7761: 
 7762: =pod
 7763: 
 7764: =head1 Course Environment Routines
 7765: 
 7766: =over 4
 7767: 
 7768: =item * &restore_course_settings()
 7769: 
 7770: =item * &store_course_settings()
 7771: 
 7772: Restores/Store indicated form parameters from the course environment.
 7773: Will not overwrite existing values of the form parameters.
 7774: 
 7775: Inputs: 
 7776: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 7777: 
 7778: a hash ref describing the data to be stored.  For example:
 7779:    
 7780: %Save_Parameters = ('Status' => 'scalar',
 7781:     'chartoutputmode' => 'scalar',
 7782:     'chartoutputdata' => 'scalar',
 7783:     'Section' => 'array',
 7784:     'Group' => 'array',
 7785:     'StudentData' => 'array',
 7786:     'Maps' => 'array');
 7787: 
 7788: Returns: both routines return nothing
 7789: 
 7790: =back
 7791: 
 7792: =cut
 7793: 
 7794: #######################################################
 7795: #######################################################
 7796: sub store_course_settings {
 7797:     return &store_settings($env{'request.course.id'},@_);
 7798: }
 7799: 
 7800: sub store_settings {
 7801:     # save to the environment
 7802:     # appenv the same items, just to be safe
 7803:     my $udom  = $env{'user.domain'};
 7804:     my $uname = $env{'user.name'};
 7805:     my ($context,$prefix,$Settings) = @_;
 7806:     my %SaveHash;
 7807:     my %AppHash;
 7808:     while (my ($setting,$type) = each(%$Settings)) {
 7809:         my $basename = join('.','internal',$context,$prefix,$setting);
 7810:         my $envname = 'environment.'.$basename;
 7811:         if (exists($env{'form.'.$setting})) {
 7812:             # Save this value away
 7813:             if ($type eq 'scalar' &&
 7814:                 (! exists($env{$envname}) || 
 7815:                  $env{$envname} ne $env{'form.'.$setting})) {
 7816:                 $SaveHash{$basename} = $env{'form.'.$setting};
 7817:                 $AppHash{$envname}   = $env{'form.'.$setting};
 7818:             } elsif ($type eq 'array') {
 7819:                 my $stored_form;
 7820:                 if (ref($env{'form.'.$setting})) {
 7821:                     $stored_form = join(',',
 7822:                                         map {
 7823:                                             &escape($_);
 7824:                                         } sort(@{$env{'form.'.$setting}}));
 7825:                 } else {
 7826:                     $stored_form = 
 7827:                         &escape($env{'form.'.$setting});
 7828:                 }
 7829:                 # Determine if the array contents are the same.
 7830:                 if ($stored_form ne $env{$envname}) {
 7831:                     $SaveHash{$basename} = $stored_form;
 7832:                     $AppHash{$envname}   = $stored_form;
 7833:                 }
 7834:             }
 7835:         }
 7836:     }
 7837:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 7838:                                           $udom,$uname);
 7839:     if ($put_result !~ /^(ok|delayed)/) {
 7840:         &Apache::lonnet::logthis('unable to save form parameters, '.
 7841:                                  'got error:'.$put_result);
 7842:     }
 7843:     # Make sure these settings stick around in this session, too
 7844:     &Apache::lonnet::appenv(\%AppHash);
 7845:     return;
 7846: }
 7847: 
 7848: sub restore_course_settings {
 7849:     return &restore_settings($env{'request.course.id'},@_);
 7850: }
 7851: 
 7852: sub restore_settings {
 7853:     my ($context,$prefix,$Settings) = @_;
 7854:     while (my ($setting,$type) = each(%$Settings)) {
 7855:         next if (exists($env{'form.'.$setting}));
 7856:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 7857:             '.'.$setting;
 7858:         if (exists($env{$envname})) {
 7859:             if ($type eq 'scalar') {
 7860:                 $env{'form.'.$setting} = $env{$envname};
 7861:             } elsif ($type eq 'array') {
 7862:                 $env{'form.'.$setting} = [ 
 7863:                                            map { 
 7864:                                                &unescape($_); 
 7865:                                            } split(',',$env{$envname})
 7866:                                            ];
 7867:             }
 7868:         }
 7869:     }
 7870: }
 7871: 
 7872: #######################################################
 7873: #######################################################
 7874: 
 7875: =pod
 7876: 
 7877: =head1 Domain E-mail Routines  
 7878: 
 7879: =over 4
 7880: 
 7881: =item * &build_recipient_list()
 7882: 
 7883: Build recipient lists for three types of e-mail:
 7884: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
 7885: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
 7886: 
 7887: Inputs:
 7888: defmail (scalar - email address of default recipient), 
 7889: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 7890: defdom (domain for which to retrieve configuration settings),
 7891: origmail (scalar - email address of recipient from loncapa.conf, 
 7892: i.e., predates configuration by DC via domainprefs.pm 
 7893: 
 7894: Returns: comma separated list of addresses to which to send e-mail.   
 7895: 
 7896: =cut
 7897: 
 7898: ############################################################
 7899: ############################################################
 7900: sub build_recipient_list {
 7901:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 7902:     my @recipients;
 7903:     my $otheremails;
 7904:     my %domconfig =
 7905:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 7906:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 7907:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 7908:             my @contacts = ('adminemail','supportemail');
 7909:             foreach my $item (@contacts) {
 7910:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
 7911:                     my $addr = $domconfig{'contacts'}{$item}; 
 7912:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
 7913:                         push(@recipients,$addr);
 7914:                     }
 7915:                 }
 7916:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 7917:             }
 7918:         }
 7919:     } elsif ($origmail ne '') {
 7920:         push(@recipients,$origmail);
 7921:     }
 7922:     if ($defmail ne '') {
 7923:         push(@recipients,$defmail);
 7924:     }
 7925:     if ($otheremails) {
 7926:         my @others;
 7927:         if ($otheremails =~ /,/) {
 7928:             @others = split(/,/,$otheremails);
 7929:         } else {
 7930:             push(@others,$otheremails);
 7931:         }
 7932:         foreach my $addr (@others) {
 7933:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 7934:                 push(@recipients,$addr);
 7935:             }
 7936:         }
 7937:     }
 7938:     my $recipientlist = join(',',@recipients); 
 7939:     return $recipientlist;
 7940: }
 7941: 
 7942: ############################################################
 7943: ############################################################
 7944: 
 7945: sub commit_customrole {
 7946:     my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
 7947:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 7948:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 7949:                          ($end?', ending '.localtime($end):'').': <b>'.
 7950:               &Apache::lonnet::assigncustomrole(
 7951:                  $udom,$uname,$url,$three,$four,$five,$end,$start).
 7952:                  '</b><br />';
 7953:     return $output;
 7954: }
 7955: 
 7956: sub commit_standardrole {
 7957:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 7958:     my ($output,$logmsg,$linefeed);
 7959:     if ($context eq 'auto') {
 7960:         $linefeed = "\n";
 7961:     } else {
 7962:         $linefeed = "<br />\n";
 7963:     }  
 7964:     if ($three eq 'st') {
 7965:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 7966:                                          $one,$two,$sec,$context);
 7967:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 7968:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 7969:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 7970:         } else {
 7971:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 7972:                ($start?', '.&mt('starting').' '.localtime($start):'').
 7973:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 7974:             if ($context eq 'auto') {
 7975:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 7976:             } else {
 7977:                $output .= '<b>'.$result.'</b>'.$linefeed.
 7978:                &mt('Add to classlist').': <b>ok</b>';
 7979:             }
 7980:             $output .= $linefeed;
 7981:         }
 7982:     } else {
 7983:         $output = &mt('Assigning').' '.$three.' in '.$url.
 7984:                ($start?', '.&mt('starting').' '.localtime($start):'').
 7985:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 7986:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start);
 7987:         if ($context eq 'auto') {
 7988:             $output .= $result.$linefeed;
 7989:         } else {
 7990:             $output .= '<b>'.$result.'</b>'.$linefeed;
 7991:         }
 7992:     }
 7993:     return $output;
 7994: }
 7995: 
 7996: sub commit_studentrole {
 7997:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 7998:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 7999:     if ($context eq 'auto') {
 8000:         $linefeed = "\n";
 8001:     } else {
 8002:         $linefeed = '<br />'."\n";
 8003:     }
 8004:     if (defined($one) && defined($two)) {
 8005:         my $cid=$one.'_'.$two;
 8006:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 8007:         my $secchange = 0;
 8008:         my $expire_role_result;
 8009:         my $modify_section_result;
 8010:         if ($oldsec ne '-1') { 
 8011:             if ($oldsec ne $sec) {
 8012:                 $secchange = 1;
 8013:                 my $now = time;
 8014:                 my $uurl='/'.$cid;
 8015:                 $uurl=~s/\_/\//g;
 8016:                 if ($oldsec) {
 8017:                     $uurl.='/'.$oldsec;
 8018:                 }
 8019:                 $oldsecurl = $uurl;
 8020:                 $expire_role_result = 
 8021:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now);
 8022:                 if ($env{'request.course.sec'} ne '') { 
 8023:                     if ($expire_role_result eq 'refused') {
 8024:                         my @roles = ('st');
 8025:                         my @statuses = ('previous');
 8026:                         my @roledoms = ($one);
 8027:                         my $withsec = 1;
 8028:                         my %roleshash = 
 8029:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 8030:                                               \@statuses,\@roles,\@roledoms,$withsec);
 8031:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 8032:                             my ($oldstart,$oldend) = 
 8033:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 8034:                             if ($oldend > 0 && $oldend <= $now) {
 8035:                                 $expire_role_result = 'ok';
 8036:                             }
 8037:                         }
 8038:                     }
 8039:                 }
 8040:                 $result = $expire_role_result;
 8041:             }
 8042:         }
 8043:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 8044:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
 8045:             if ($modify_section_result =~ /^ok/) {
 8046:                 if ($secchange == 1) {
 8047:                     if ($sec eq '') {
 8048:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 8049:                     } else {
 8050:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 8051:                     }
 8052:                 } elsif ($oldsec eq '-1') {
 8053:                     if ($sec eq '') {
 8054:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 8055:                     } else {
 8056:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8057:                     }
 8058:                 } else {
 8059:                     if ($sec eq '') {
 8060:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 8061:                     } else {
 8062:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8063:                     }
 8064:                 }
 8065:             } else {
 8066:                 if ($secchange) {       
 8067:                     $$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;
 8068:                 } else {
 8069:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 8070:                 }
 8071:             }
 8072:             $result = $modify_section_result;
 8073:         } elsif ($secchange == 1) {
 8074:             if ($oldsec eq '') {
 8075:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 8076:             } else {
 8077:                 $$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;
 8078:             }
 8079:             if ($expire_role_result eq 'refused') {
 8080:                 my $newsecurl = '/'.$cid;
 8081:                 $newsecurl =~ s/\_/\//g;
 8082:                 if ($sec ne '') {
 8083:                     $newsecurl.='/'.$sec;
 8084:                 }
 8085:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 8086:                     if ($sec eq '') {
 8087:                         $$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;
 8088:                     } else {
 8089:                         $$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;
 8090:                     }
 8091:                 }
 8092:             }
 8093:         }
 8094:     } else {
 8095:         $$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;
 8096:         $result = "error: incomplete course id\n";
 8097:     }
 8098:     return $result;
 8099: }
 8100: 
 8101: ############################################################
 8102: ############################################################
 8103: 
 8104: sub check_clone {
 8105:     my ($args,$linefeed) = @_;
 8106:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 8107:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 8108:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 8109:     my $clonemsg;
 8110:     my $can_clone = 0;
 8111: 
 8112:     if ($clonehome eq 'no_host') {
 8113:         $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'});     
 8114:     } else {
 8115: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 8116: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 8117: 	    $can_clone = 1;
 8118: 	} else {
 8119: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 8120: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 8121: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 8122:             if (grep(/^\*$/,@cloners)) {
 8123:                 $can_clone = 1;
 8124:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 8125:                 $can_clone = 1;
 8126:             } else {
 8127: 	        my %roleshash =
 8128: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 8129: 					 $args->{'ccdomain'},
 8130:                                          'userroles',['active'],['cc'],
 8131: 					 [$args->{'clonedomain'}]);
 8132: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 8133: 		    $can_clone = 1;
 8134: 	        } else {
 8135:                     $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'});
 8136: 	        }
 8137: 	    }
 8138:         }
 8139:     }
 8140:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 8141: }
 8142: 
 8143: sub construct_course {
 8144:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 8145:     my $outcome;
 8146:     my $linefeed =  '<br />'."\n";
 8147:     if ($context eq 'auto') {
 8148:         $linefeed = "\n";
 8149:     }
 8150: 
 8151: #
 8152: # Are we cloning?
 8153: #
 8154:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 8155:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 8156: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 8157: 	if ($context ne 'auto') {
 8158:             if ($clonemsg ne '') {
 8159: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 8160:             }
 8161: 	}
 8162: 	$outcome .= $clonemsg.$linefeed;
 8163: 
 8164:         if (!$can_clone) {
 8165: 	    return (0,$outcome);
 8166: 	}
 8167:     }
 8168: 
 8169: #
 8170: # Open course
 8171: #
 8172:     my $crstype = lc($args->{'crstype'});
 8173:     my %cenv=();
 8174:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 8175:                                              $args->{'cdescr'},
 8176:                                              $args->{'curl'},
 8177:                                              $args->{'course_home'},
 8178:                                              $args->{'nonstandard'},
 8179:                                              $args->{'crscode'},
 8180:                                              $args->{'ccuname'}.':'.
 8181:                                              $args->{'ccdomain'},
 8182:                                              $args->{'crstype'});
 8183: 
 8184:     # Note: The testing routines depend on this being output; see 
 8185:     # Utils::Course. This needs to at least be output as a comment
 8186:     # if anyone ever decides to not show this, and Utils::Course::new
 8187:     # will need to be suitably modified.
 8188:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 8189: #
 8190: # Check if created correctly
 8191: #
 8192:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 8193:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 8194:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 8195: 
 8196: #
 8197: # Do the cloning
 8198: #   
 8199:     if ($can_clone && $cloneid) {
 8200: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 8201: 	if ($context ne 'auto') {
 8202: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 8203: 	}
 8204: 	$outcome .= $clonemsg.$linefeed;
 8205: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 8206: # Copy all files
 8207: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 8208: # Restore URL
 8209: 	$cenv{'url'}=$oldcenv{'url'};
 8210: # Restore title
 8211: 	$cenv{'description'}=$oldcenv{'description'};
 8212: # Mark as cloned
 8213: 	$cenv{'clonedfrom'}=$cloneid;
 8214: # Need to clone grading mode
 8215:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 8216:         $cenv{'grading'}=$newenv{'grading'};
 8217: # Do not clone these environment entries
 8218:         &Apache::lonnet::del('environment',
 8219:                   ['default_enrollment_start_date',
 8220:                    'default_enrollment_end_date',
 8221:                    'question.email',
 8222:                    'policy.email',
 8223:                    'comment.email',
 8224:                    'pch.users.denied',
 8225:                    'plc.users.denied'],
 8226:                    $$crsudom,$$crsunum);
 8227:     }
 8228: 
 8229: #
 8230: # Set environment (will override cloned, if existing)
 8231: #
 8232:     my @sections = ();
 8233:     my @xlists = ();
 8234:     if ($args->{'crstype'}) {
 8235:         $cenv{'type'}=$args->{'crstype'};
 8236:     }
 8237:     if ($args->{'crsid'}) {
 8238:         $cenv{'courseid'}=$args->{'crsid'};
 8239:     }
 8240:     if ($args->{'crscode'}) {
 8241:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 8242:     }
 8243:     if ($args->{'crsquota'} ne '') {
 8244:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 8245:     } else {
 8246:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 8247:     }
 8248:     if ($args->{'ccuname'}) {
 8249:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 8250:                                         ':'.$args->{'ccdomain'};
 8251:     } else {
 8252:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 8253:     }
 8254:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 8255:     if ($args->{'crssections'}) {
 8256:         $cenv{'internal.sectionnums'} = '';
 8257:         if ($args->{'crssections'} =~ m/,/) {
 8258:             @sections = split/,/,$args->{'crssections'};
 8259:         } else {
 8260:             $sections[0] = $args->{'crssections'};
 8261:         }
 8262:         if (@sections > 0) {
 8263:             foreach my $item (@sections) {
 8264:                 my ($sec,$gp) = split/:/,$item;
 8265:                 my $class = $args->{'crscode'}.$sec;
 8266:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 8267:                 $cenv{'internal.sectionnums'} .= $item.',';
 8268:                 unless ($addcheck eq 'ok') {
 8269:                     push @badclasses, $class;
 8270:                 }
 8271:             }
 8272:             $cenv{'internal.sectionnums'} =~ s/,$//;
 8273:         }
 8274:     }
 8275: # do not hide course coordinator from staff listing, 
 8276: # even if privileged
 8277:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 8278: # add crosslistings
 8279:     if ($args->{'crsxlist'}) {
 8280:         $cenv{'internal.crosslistings'}='';
 8281:         if ($args->{'crsxlist'} =~ m/,/) {
 8282:             @xlists = split/,/,$args->{'crsxlist'};
 8283:         } else {
 8284:             $xlists[0] = $args->{'crsxlist'};
 8285:         }
 8286:         if (@xlists > 0) {
 8287:             foreach my $item (@xlists) {
 8288:                 my ($xl,$gp) = split/:/,$item;
 8289:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 8290:                 $cenv{'internal.crosslistings'} .= $item.',';
 8291:                 unless ($addcheck eq 'ok') {
 8292:                     push @badclasses, $xl;
 8293:                 }
 8294:             }
 8295:             $cenv{'internal.crosslistings'} =~ s/,$//;
 8296:         }
 8297:     }
 8298:     if ($args->{'autoadds'}) {
 8299:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 8300:     }
 8301:     if ($args->{'autodrops'}) {
 8302:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 8303:     }
 8304: # check for notification of enrollment changes
 8305:     my @notified = ();
 8306:     if ($args->{'notify_owner'}) {
 8307:         if ($args->{'ccuname'} ne '') {
 8308:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 8309:         }
 8310:     }
 8311:     if ($args->{'notify_dc'}) {
 8312:         if ($uname ne '') { 
 8313:             push(@notified,$uname.':'.$udom);
 8314:         }
 8315:     }
 8316:     if (@notified > 0) {
 8317:         my $notifylist;
 8318:         if (@notified > 1) {
 8319:             $notifylist = join(',',@notified);
 8320:         } else {
 8321:             $notifylist = $notified[0];
 8322:         }
 8323:         $cenv{'internal.notifylist'} = $notifylist;
 8324:     }
 8325:     if (@badclasses > 0) {
 8326:         my %lt=&Apache::lonlocal::texthash(
 8327:                 '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',
 8328:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 8329:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 8330:         );
 8331:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 8332:                            ' ('.$lt{'adby'}.')';
 8333:         if ($context eq 'auto') {
 8334:             $outcome .= $badclass_msg.$linefeed;
 8335:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 8336:             foreach my $item (@badclasses) {
 8337:                 if ($context eq 'auto') {
 8338:                     $outcome .= " - $item\n";
 8339:                 } else {
 8340:                     $outcome .= "<li>$item</li>\n";
 8341:                 }
 8342:             }
 8343:             if ($context eq 'auto') {
 8344:                 $outcome .= $linefeed;
 8345:             } else {
 8346:                 $outcome .= "</ul><br /><br /></div>\n";
 8347:             }
 8348:         } 
 8349:     }
 8350:     if ($args->{'no_end_date'}) {
 8351:         $args->{'endaccess'} = 0;
 8352:     }
 8353:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 8354:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 8355:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 8356:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 8357:     if ($args->{'showphotos'}) {
 8358:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 8359:     }
 8360:     $cenv{'internal.authtype'} = $args->{'authtype'};
 8361:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 8362:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 8363:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 8364:             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'); 
 8365:             if ($context eq 'auto') {
 8366:                 $outcome .= $krb_msg;
 8367:             } else {
 8368:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 8369:             }
 8370:             $outcome .= $linefeed;
 8371:         }
 8372:     }
 8373:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 8374:        if ($args->{'setpolicy'}) {
 8375:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 8376:        }
 8377:        if ($args->{'setcontent'}) {
 8378:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 8379:        }
 8380:     }
 8381:     if ($args->{'reshome'}) {
 8382: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 8383: 	$cenv{'reshome'}=~s/\/+$/\//;
 8384:     }
 8385: #
 8386: # course has keyed access
 8387: #
 8388:     if ($args->{'setkeys'}) {
 8389:        $cenv{'keyaccess'}='yes';
 8390:     }
 8391: # if specified, key authority is not course, but user
 8392: # only active if keyaccess is yes
 8393:     if ($args->{'keyauth'}) {
 8394: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 8395: 	$user = &LONCAPA::clean_username($user);
 8396: 	$domain = &LONCAPA::clean_username($domain);
 8397: 	if ($user ne '' && $domain ne '') {
 8398: 	    $cenv{'keyauth'}=$user.':'.$domain;
 8399: 	}
 8400:     }
 8401: 
 8402:     if ($args->{'disresdis'}) {
 8403:         $cenv{'pch.roles.denied'}='st';
 8404:     }
 8405:     if ($args->{'disablechat'}) {
 8406:         $cenv{'plc.roles.denied'}='st';
 8407:     }
 8408: 
 8409:     # Record we've not yet viewed the Course Initialization Helper for this 
 8410:     # course
 8411:     $cenv{'course.helper.not.run'} = 1;
 8412:     #
 8413:     # Use new Randomseed
 8414:     #
 8415:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 8416:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 8417:     #
 8418:     # The encryption code and receipt prefix for this course
 8419:     #
 8420:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 8421:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 8422:     #
 8423:     # By default, use standard grading
 8424:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 8425: 
 8426:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 8427:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 8428: #
 8429: # Open all assignments
 8430: #
 8431:     if ($args->{'openall'}) {
 8432:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 8433:        my %storecontent = ($storeunder         => time,
 8434:                            $storeunder.'.type' => 'date_start');
 8435:        
 8436:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 8437:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 8438:    }
 8439: #
 8440: # Set first page
 8441: #
 8442:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 8443: 	    || ($cloneid)) {
 8444: 	use LONCAPA::map;
 8445: 	$outcome .= &mt('Setting first resource').': ';
 8446: 
 8447: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 8448:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 8449: 
 8450:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 8451:         my $title; my $url;
 8452:         if ($args->{'firstres'} eq 'syl') {
 8453: 	    $title='Syllabus';
 8454:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 8455:         } else {
 8456:             $title='Navigate Contents';
 8457:             $url='/adm/navmaps';
 8458:         }
 8459: 
 8460:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 8461: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 8462: 
 8463: 	if ($errtext) { $fatal=2; }
 8464:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 8465:     }
 8466: 
 8467:     return (1,$outcome);
 8468: }
 8469: 
 8470: ############################################################
 8471: ############################################################
 8472: 
 8473: sub course_type {
 8474:     my ($cid) = @_;
 8475:     if (!defined($cid)) {
 8476:         $cid = $env{'request.course.id'};
 8477:     }
 8478:     if (defined($env{'course.'.$cid.'.type'})) {
 8479:         return $env{'course.'.$cid.'.type'};
 8480:     } else {
 8481:         return 'Course';
 8482:     }
 8483: }
 8484: 
 8485: sub group_term {
 8486:     my $crstype = &course_type();
 8487:     my %names = (
 8488:                   'Course' => 'group',
 8489:                   'Group' => 'team',
 8490:                 );
 8491:     return $names{$crstype};
 8492: }
 8493: 
 8494: sub icon {
 8495:     my ($file)=@_;
 8496:     my $curfext = lc((split(/\./,$file))[-1]);
 8497:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 8498:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 8499:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 8500: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 8501: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 8502: 	            $curfext.".gif") {
 8503: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 8504: 		$curfext.".gif";
 8505: 	}
 8506:     }
 8507:     return &lonhttpdurl($iconname);
 8508: } 
 8509: 
 8510: sub lonhttpd_port {
 8511:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 8512:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 8513:     # IE doesn't like a secure page getting images from a non-secure
 8514:     # port (when logging we haven't parsed the browser type so default
 8515:     # back to secure
 8516:     if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
 8517: 	&& $ENV{'SERVER_PORT'} == 443) {
 8518: 	return 443;
 8519:     }
 8520:     return $lonhttpd_port;
 8521: 
 8522: }
 8523: 
 8524: sub lonhttpdurl {
 8525:     my ($url)=@_;
 8526: 
 8527:     my $lonhttpd_port = &lonhttpd_port();
 8528:     if ($lonhttpd_port == 443) {
 8529: 	return 'https://'.$ENV{'SERVER_NAME'}.$url;
 8530:     }
 8531:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 8532: }
 8533: 
 8534: sub connection_aborted {
 8535:     my ($r)=@_;
 8536:     $r->print(" ");$r->rflush();
 8537:     my $c = $r->connection;
 8538:     return $c->aborted();
 8539: }
 8540: 
 8541: #    Escapes strings that may have embedded 's that will be put into
 8542: #    strings as 'strings'.
 8543: sub escape_single {
 8544:     my ($input) = @_;
 8545:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 8546:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 8547:     return $input;
 8548: }
 8549: 
 8550: #  Same as escape_single, but escape's "'s  This 
 8551: #  can be used for  "strings"
 8552: sub escape_double {
 8553:     my ($input) = @_;
 8554:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 8555:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 8556:     return $input;
 8557: }
 8558:  
 8559: #   Escapes the last element of a full URL.
 8560: sub escape_url {
 8561:     my ($url)   = @_;
 8562:     my @urlslices = split(/\//, $url,-1);
 8563:     my $lastitem = &escape(pop(@urlslices));
 8564:     return join('/',@urlslices).'/'.$lastitem;
 8565: }
 8566: 
 8567: # -------------------------------------------------------- Initliaze user login
 8568: sub init_user_environment {
 8569:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 8570:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 8571: 
 8572:     my $public=($username eq 'public' && $domain eq 'public');
 8573: 
 8574: # See if old ID present, if so, remove
 8575: 
 8576:     my ($filename,$cookie,$userroles);
 8577:     my $now=time;
 8578: 
 8579:     if ($public) {
 8580: 	my $max_public=100;
 8581: 	my $oldest;
 8582: 	my $oldest_time=0;
 8583: 	for(my $next=1;$next<=$max_public;$next++) {
 8584: 	    if (-e $lonids."/publicuser_$next.id") {
 8585: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 8586: 		if ($mtime<$oldest_time || !$oldest_time) {
 8587: 		    $oldest_time=$mtime;
 8588: 		    $oldest=$next;
 8589: 		}
 8590: 	    } else {
 8591: 		$cookie="publicuser_$next";
 8592: 		last;
 8593: 	    }
 8594: 	}
 8595: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 8596:     } else {
 8597: 	# if this isn't a robot, kill any existing non-robot sessions
 8598: 	if (!$args->{'robot'}) {
 8599: 	    opendir(DIR,$lonids);
 8600: 	    while ($filename=readdir(DIR)) {
 8601: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 8602: 		    unlink($lonids.'/'.$filename);
 8603: 		}
 8604: 	    }
 8605: 	    closedir(DIR);
 8606: 	}
 8607: # Give them a new cookie
 8608: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 8609: 		                   : $now);
 8610: 	$cookie="$username\_$id\_$domain\_$authhost";
 8611:     
 8612: # Initialize roles
 8613: 
 8614: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 8615:     }
 8616: # ------------------------------------ Check browser type and MathML capability
 8617: 
 8618:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 8619:         $clientunicode,$clientos) = &decode_user_agent($r);
 8620: 
 8621: # -------------------------------------- Any accessibility options to remember?
 8622:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 8623: 	foreach my $option ('imagesuppress','appletsuppress',
 8624: 			    'embedsuppress','fontenhance','blackwhite') {
 8625: 	    if ($form->{$option} eq 'true') {
 8626: 		&Apache::lonnet::put('environment',{$option => 'on'},
 8627: 				     $domain,$username);
 8628: 	    } else {
 8629: 		&Apache::lonnet::del('environment',[$option],
 8630: 				     $domain,$username);
 8631: 	    }
 8632: 	}
 8633:     }
 8634: # ------------------------------------------------------------- Get environment
 8635: 
 8636:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 8637:     my ($tmp) = keys(%userenv);
 8638:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8639: 	# default remote control to off
 8640: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 8641:     } else {
 8642: 	undef(%userenv);
 8643:     }
 8644:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 8645: 	$form->{'interface'}=$userenv{'interface'};
 8646:     }
 8647:     $env{'environment.remote'}=$userenv{'remote'};
 8648:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 8649: 
 8650: # --------------- Do not trust query string to be put directly into environment
 8651:     foreach my $option ('imagesuppress','appletsuppress',
 8652: 			'embedsuppress','fontenhance','blackwhite',
 8653: 			'interface','localpath','localres') {
 8654: 	$form->{$option}=~s/[\n\r\=]//gs;
 8655:     }
 8656: # --------------------------------------------------------- Write first profile
 8657: 
 8658:     {
 8659: 	my %initial_env = 
 8660: 	    ("user.name"          => $username,
 8661: 	     "user.domain"        => $domain,
 8662: 	     "user.home"          => $authhost,
 8663: 	     "browser.type"       => $clientbrowser,
 8664: 	     "browser.version"    => $clientversion,
 8665: 	     "browser.mathml"     => $clientmathml,
 8666: 	     "browser.unicode"    => $clientunicode,
 8667: 	     "browser.os"         => $clientos,
 8668: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 8669: 	     "request.course.fn"  => '',
 8670: 	     "request.course.uri" => '',
 8671: 	     "request.course.sec" => '',
 8672: 	     "request.role"       => 'cm',
 8673: 	     "request.role.adv"   => $env{'user.adv'},
 8674: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 8675: 
 8676:         if ($form->{'localpath'}) {
 8677: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 8678: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 8679:         }
 8680: 	
 8681: 	if ($public) {
 8682: 	    $initial_env{"environment.remote"} = "off";
 8683: 	}
 8684: 	if ($form->{'interface'}) {
 8685: 	    $form->{'interface'}=~s/\W//gs;
 8686: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 8687: 	    $env{'browser.interface'}=$form->{'interface'};
 8688: 	    foreach my $option ('imagesuppress','appletsuppress',
 8689: 				'embedsuppress','fontenhance','blackwhite') {
 8690: 		if (($form->{$option} eq 'true') ||
 8691: 		    ($userenv{$option} eq 'on')) {
 8692: 		    $initial_env{"browser.$option"} = "on";
 8693: 		}
 8694: 	    }
 8695: 	}
 8696: 
 8697: 	$env{'user.environment'} = "$lonids/$cookie.id";
 8698: 	
 8699: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 8700: 		 &GDBM_WRCREAT(),0640)) {
 8701: 	    &_add_to_env(\%disk_env,\%initial_env);
 8702: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 8703: 	    &_add_to_env(\%disk_env,$userroles);
 8704: 	    if (ref($args->{'extra_env'})) {
 8705: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 8706: 	    }
 8707: 	    untie(%disk_env);
 8708: 	} else {
 8709: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 8710: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 8711: 	    return 'error: '.$!;
 8712: 	}
 8713:     }
 8714:     $env{'request.role'}='cm';
 8715:     $env{'request.role.adv'}=$env{'user.adv'};
 8716:     $env{'browser.type'}=$clientbrowser;
 8717: 
 8718:     return $cookie;
 8719: 
 8720: }
 8721: 
 8722: sub _add_to_env {
 8723:     my ($idf,$env_data,$prefix) = @_;
 8724:     while (my ($key,$value) = each(%$env_data)) {
 8725: 	$idf->{$prefix.$key} = $value;
 8726: 	$env{$prefix.$key}   = $value;
 8727:     }
 8728: }
 8729: 
 8730: 
 8731: =pod
 8732: 
 8733: =back
 8734: 
 8735: =cut
 8736: 
 8737: 1;
 8738: __END__;
 8739: 

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