File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.664: download - view: text, annotated - select for diffs
Sun Jul 6 05:01:52 2008 UTC (15 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Mising <span>
- Include $context argument in sub commit_customrole() and pass along to &lonnet::assigncustomrole().

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.664 2008/07/06 05:01:52 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: use DateTime::TimeZone;
   71: 
   72: # ---------------------------------------------- Designs
   73: use vars qw(%defaultdesign);
   74: 
   75: my $readit;
   76: 
   77: 
   78: ##
   79: ## Global Variables
   80: ##
   81: 
   82: 
   83: # ----------------------------------------------- SSI with retries:
   84: #
   85: 
   86: =pod
   87: 
   88: =head1 Server Side include with retries:
   89: 
   90: =over 4
   91: 
   92: =item * &ssi_with_retries(resource,retries form)
   93: 
   94: Performs an ssi with some number of retries.  Retries continue either
   95: until the result is ok or until the retry count supplied by the
   96: caller is exhausted.  
   97: 
   98: Inputs:
   99: 
  100: =over 4
  101: 
  102: resource   - Identifies the resource to insert.
  103: 
  104: retries    - Count of the number of retries allowed.
  105: 
  106: form       - Hash that identifies the rendering options.
  107: 
  108: =back
  109: 
  110: Returns:
  111: 
  112: =over 4
  113: 
  114: content    - The content of the response.  If retries were exhausted this is empty.
  115: 
  116: response   - The response from the last attempt (which may or may not have been successful.
  117: 
  118: =back
  119: 
  120: =back
  121: 
  122: =cut
  123: 
  124: sub ssi_with_retries {
  125:     my ($resource, $retries, %form) = @_;
  126: 
  127: 
  128:     my $ok = 0;			# True if we got a good response.
  129:     my $content;
  130:     my $response;
  131: 
  132:     # Try to get the ssi done. within the retries count:
  133: 
  134:     do {
  135: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  136: 	$ok      = $response->is_success;
  137:         if (!$ok) {
  138:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  139:         }
  140: 	$retries--;
  141:     } while (!$ok && ($retries > 0));
  142: 
  143:     if (!$ok) {
  144: 	$content = '';		# On error return an empty content.
  145:     }
  146:     return ($content, $response);
  147: 
  148: }
  149: 
  150: 
  151: 
  152: # ----------------------------------------------- Filetypes/Languages/Copyright
  153: my %language;
  154: my %supported_language;
  155: my %cprtag;
  156: my %scprtag;
  157: my %fe; my %fd; my %fm;
  158: my %category_extensions;
  159: 
  160: # ---------------------------------------------- Thesaurus variables
  161: #
  162: # %Keywords:
  163: #      A hash used by &keyword to determine if a word is considered a keyword.
  164: # $thesaurus_db_file 
  165: #      Scalar containing the full path to the thesaurus database.
  166: 
  167: my %Keywords;
  168: my $thesaurus_db_file;
  169: 
  170: #
  171: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  172: # thesaurus.tab, and filecategories.tab.
  173: #
  174: BEGIN {
  175:     # Variable initialization
  176:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  177:     #
  178:     unless ($readit) {
  179: # ------------------------------------------------------------------- languages
  180:     {
  181:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  182:                                    '/language.tab';
  183:         if ( open(my $fh,"<$langtabfile") ) {
  184:             while (my $line = <$fh>) {
  185:                 next if ($line=~/^\#/);
  186:                 chomp($line);
  187:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  188:                 $language{$key}=$val.' - '.$enc;
  189:                 if ($sup) {
  190:                     $supported_language{$key}=$sup;
  191:                 }
  192:             }
  193:             close($fh);
  194:         }
  195:     }
  196: # ------------------------------------------------------------------ copyrights
  197:     {
  198:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  199:                                   '/copyright.tab';
  200:         if ( open (my $fh,"<$copyrightfile") ) {
  201:             while (my $line = <$fh>) {
  202:                 next if ($line=~/^\#/);
  203:                 chomp($line);
  204:                 my ($key,$val)=(split(/\s+/,$line,2));
  205:                 $cprtag{$key}=$val;
  206:             }
  207:             close($fh);
  208:         }
  209:     }
  210: # ----------------------------------------------------------- source copyrights
  211:     {
  212:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  213:                                   '/source_copyright.tab';
  214:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  215:             while (my $line = <$fh>) {
  216:                 next if ($line =~ /^\#/);
  217:                 chomp($line);
  218:                 my ($key,$val)=(split(/\s+/,$line,2));
  219:                 $scprtag{$key}=$val;
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: 
  225: # -------------------------------------------------------------- default domain designs
  226:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  227:     my $designfile = $designdir.'/default.tab';
  228:     if ( open (my $fh,"<$designfile") ) {
  229:         while (my $line = <$fh>) {
  230:             next if ($line =~ /^\#/);
  231:             chomp($line);
  232:             my ($key,$val)=(split(/\=/,$line));
  233:             if ($val) { $defaultdesign{$key}=$val; }
  234:         }
  235:         close($fh);
  236:     }
  237: 
  238: # ------------------------------------------------------------- file categories
  239:     {
  240:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  241:                                   '/filecategories.tab';
  242:         if ( open (my $fh,"<$categoryfile") ) {
  243: 	    while (my $line = <$fh>) {
  244: 		next if ($line =~ /^\#/);
  245: 		chomp($line);
  246:                 my ($extension,$category)=(split(/\s+/,$line,2));
  247:                 push @{$category_extensions{lc($category)}},$extension;
  248:             }
  249:             close($fh);
  250:         }
  251: 
  252:     }
  253: # ------------------------------------------------------------------ file types
  254:     {
  255:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  256:                '/filetypes.tab';
  257:         if ( open (my $fh,"<$typesfile") ) {
  258:             while (my $line = <$fh>) {
  259: 		next if ($line =~ /^\#/);
  260: 		chomp($line);
  261:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  262:                 if ($descr ne '') {
  263:                     $fe{$ending}=lc($emb);
  264:                     $fd{$ending}=$descr;
  265:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  266:                 }
  267:             }
  268:             close($fh);
  269:         }
  270:     }
  271:     &Apache::lonnet::logthis(
  272:               "<font color=yellow>INFO: Read file types</font>");
  273:     $readit=1;
  274:     }  # end of unless($readit) 
  275:     
  276: }
  277: 
  278: ###############################################################
  279: ##           HTML and Javascript Helper Functions            ##
  280: ###############################################################
  281: 
  282: =pod 
  283: 
  284: =head1 HTML and Javascript Functions
  285: 
  286: =over 4
  287: 
  288: =item * &browser_and_searcher_javascript()
  289: 
  290: X<browsing, javascript>X<searching, javascript>Returns a string
  291: containing javascript with two functions, C<openbrowser> and
  292: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  293: tags.
  294: 
  295: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  296: 
  297: inputs: formname, elementname, only, omit
  298: 
  299: formname and elementname indicate the name of the html form and name of
  300: the element that the results of the browsing selection are to be placed in. 
  301: 
  302: Specifying 'only' will restrict the browser to displaying only files
  303: with the given extension.  Can be a comma separated list.
  304: 
  305: Specifying 'omit' will restrict the browser to NOT displaying files
  306: with the given extension.  Can be a comma separated list.
  307: 
  308: =item * &opensearcher(formname,elementname) [javascript]
  309: 
  310: Inputs: formname, elementname
  311: 
  312: formname and elementname specify the name of the html form and the name
  313: of the element the selection from the search results will be placed in.
  314: 
  315: =cut
  316: 
  317: sub browser_and_searcher_javascript {
  318:     my ($mode)=@_;
  319:     if (!defined($mode)) { $mode='edit'; }
  320:     my $resurl=&escape_single(&lastresurl());
  321:     return <<END;
  322: // <!-- BEGIN LON-CAPA Internal
  323:     var editbrowser = null;
  324:     function openbrowser(formname,elementname,only,omit,titleelement) {
  325:         var url = '$resurl/?';
  326:         if (editbrowser == null) {
  327:             url += 'launch=1&';
  328:         }
  329:         url += 'catalogmode=interactive&';
  330:         url += 'mode=$mode&';
  331:         url += 'inhibitmenu=yes&';
  332:         url += 'form=' + formname + '&';
  333:         if (only != null) {
  334:             url += 'only=' + only + '&';
  335:         } else {
  336:             url += 'only=&';
  337: 	}
  338:         if (omit != null) {
  339:             url += 'omit=' + omit + '&';
  340:         } else {
  341:             url += 'omit=&';
  342: 	}
  343:         if (titleelement != null) {
  344:             url += 'titleelement=' + titleelement + '&';
  345:         } else {
  346: 	    url += 'titleelement=&';
  347: 	}
  348:         url += 'element=' + elementname + '';
  349:         var title = 'Browser';
  350:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  351:         options += ',width=700,height=600';
  352:         editbrowser = open(url,title,options,'1');
  353:         editbrowser.focus();
  354:     }
  355:     var editsearcher;
  356:     function opensearcher(formname,elementname,titleelement) {
  357:         var url = '/adm/searchcat?';
  358:         if (editsearcher == null) {
  359:             url += 'launch=1&';
  360:         }
  361:         url += 'catalogmode=interactive&';
  362:         url += 'mode=$mode&';
  363:         url += 'form=' + formname + '&';
  364:         if (titleelement != null) {
  365:             url += 'titleelement=' + titleelement + '&';
  366:         } else {
  367: 	    url += 'titleelement=&';
  368: 	}
  369:         url += 'element=' + elementname + '';
  370:         var title = 'Search';
  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  372:         options += ',width=700,height=600';
  373:         editsearcher = open(url,title,options,'1');
  374:         editsearcher.focus();
  375:     }
  376: // END LON-CAPA Internal -->
  377: END
  378: }
  379: 
  380: sub lastresurl {
  381:     if ($env{'environment.lastresurl'}) {
  382: 	return $env{'environment.lastresurl'}
  383:     } else {
  384: 	return '/res';
  385:     }
  386: }
  387: 
  388: sub storeresurl {
  389:     my $resurl=&Apache::lonnet::clutter(shift);
  390:     unless ($resurl=~/^\/res/) { return 0; }
  391:     $resurl=~s/\/$//;
  392:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  393:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  394:     return 1;
  395: }
  396: 
  397: sub studentbrowser_javascript {
  398:    unless (
  399:             (($env{'request.course.id'}) && 
  400:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  401: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  402: 					  '/'.$env{'request.course.sec'})
  403: 	      ))
  404:          || ($env{'request.role'}=~/^(au|dc|su)/)
  405:           ) { return ''; }  
  406:    return (<<'ENDSTDBRW');
  407: <script type="text/javascript" language="Javascript" >
  408:     var stdeditbrowser;
  409:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  410:         var url = '/adm/pickstudent?';
  411:         var filter;
  412: 	if (!ignorefilter) {
  413: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  414: 	}
  415:         if (filter != null) {
  416:            if (filter != '') {
  417:                url += 'filter='+filter+'&';
  418: 	   }
  419:         }
  420:         url += 'form=' + formname + '&unameelement='+uname+
  421:                                     '&udomelement='+udom;
  422: 	if (roleflag) { url+="&roles=1"; }
  423:         var title = 'Student_Browser';
  424:         var options = 'scrollbars=1,resizable=1,menubar=0';
  425:         options += ',width=700,height=600';
  426:         stdeditbrowser = open(url,title,options,'1');
  427:         stdeditbrowser.focus();
  428:     }
  429: </script>
  430: ENDSTDBRW
  431: }
  432: 
  433: sub selectstudent_link {
  434:    my ($form,$unameele,$udomele)=@_;
  435:    if ($env{'request.course.id'}) {  
  436:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  437: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  438: 					'/'.$env{'request.course.sec'})) {
  439: 	   return '';
  440:        }
  441:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  442:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  443:    }
  444:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  445:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  446:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  447:    }
  448:    return '';
  449: }
  450: 
  451: sub authorbrowser_javascript {
  452:     return <<"ENDAUTHORBRW";
  453: <script type="text/javascript">
  454: var stdeditbrowser;
  455: 
  456: function openauthorbrowser(formname,udom) {
  457:     var url = '/adm/pickauthor?';
  458:     url += 'form='+formname+'&roledom='+udom;
  459:     var title = 'Author_Browser';
  460:     var options = 'scrollbars=1,resizable=1,menubar=0';
  461:     options += ',width=700,height=600';
  462:     stdeditbrowser = open(url,title,options,'1');
  463:     stdeditbrowser.focus();
  464: }
  465: 
  466: </script>
  467: ENDAUTHORBRW
  468: }
  469: 
  470: sub coursebrowser_javascript {
  471:     my ($domainfilter,$sec_element,$formname)=@_;
  472:     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');
  473:    my $output = '
  474: <script type="text/javascript">
  475:     var stdeditbrowser;'."\n";
  476:    $output .= <<"ENDSTDBRW";
  477:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  478:         var url = '/adm/pickcourse?';
  479:         var domainfilter = '';
  480:         var formid = getFormIdByName(formname);
  481:         if (formid > -1) {
  482:             var domid = getIndexByName(formid,udom);
  483:             if (domid > -1) {
  484:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  485:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  486:                 }
  487:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  488:                     domainfilter=document.forms[formid].elements[domid].value;
  489:                 }
  490:             }
  491:         }
  492:         if (domainfilter != null) {
  493:            if (domainfilter != '') {
  494:                url += 'domainfilter='+domainfilter+'&';
  495: 	   }
  496:         }
  497:         url += 'form=' + formname + '&cnumelement='+uname+
  498: 	                            '&cdomelement='+udom+
  499:                                     '&cnameelement='+desc;
  500:         if (extra_element !=null && extra_element != '') {
  501:             if (formname == 'rolechoice' || formname == 'studentform') {
  502:                 url += '&roleelement='+extra_element;
  503:                 if (domainfilter == null || domainfilter == '') {
  504:                     url += '&domainfilter='+extra_element;
  505:                 }
  506:             }
  507:             else {
  508:                 if (formname == 'portform') {
  509:                     url += '&setroles='+extra_element;
  510:                 }
  511:             }     
  512:         }
  513:         if (multflag !=null && multflag != '') {
  514:             url += '&multiple='+multflag;
  515:         }
  516:         if (crstype == 'Course/Group') {
  517:             if (formname == 'cu') {
  518:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  519:                 if (crstype == "") {
  520:                     alert("$crs_or_grp_alert");
  521:                     return;
  522:                 }
  523:             }
  524:         }
  525:         if (crstype !=null && crstype != '') {
  526:             url += '&type='+crstype;
  527:         }
  528:         var title = 'Course_Browser';
  529:         var options = 'scrollbars=1,resizable=1,menubar=0';
  530:         options += ',width=700,height=600';
  531:         stdeditbrowser = open(url,title,options,'1');
  532:         stdeditbrowser.focus();
  533:     }
  534: 
  535:     function getFormIdByName(formname) {
  536:         for (var i=0;i<document.forms.length;i++) {
  537:             if (document.forms[i].name == formname) {
  538:                 return i;
  539:             }
  540:         }
  541:         return -1; 
  542:     }
  543: 
  544:     function getIndexByName(formid,item) {
  545:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  546:             if (document.forms[formid].elements[i].name == item) {
  547:                 return i;
  548:             }
  549:         }
  550:         return -1;
  551:     }
  552: ENDSTDBRW
  553:     if ($sec_element ne '') {
  554:         $output .= &setsec_javascript($sec_element,$formname);
  555:     }
  556:     $output .= '
  557: </script>';
  558:     return $output;
  559: }
  560: 
  561: sub setsec_javascript {
  562:     my ($sec_element,$formname) = @_;
  563:     my $setsections = qq|
  564: function setSect(sectionlist) {
  565:     var sectionsArray = new Array();
  566:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  567:         sectionsArray = sectionlist.split(",");
  568:     }
  569:     var numSections = sectionsArray.length;
  570:     document.$formname.$sec_element.length = 0;
  571:     if (numSections == 0) {
  572:         document.$formname.$sec_element.multiple=false;
  573:         document.$formname.$sec_element.size=1;
  574:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  575:     } else {
  576:         if (numSections == 1) {
  577:             document.$formname.$sec_element.multiple=false;
  578:             document.$formname.$sec_element.size=1;
  579:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  580:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  581:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  582:         } else {
  583:             for (var i=0; i<numSections; i++) {
  584:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  585:             }
  586:             document.$formname.$sec_element.multiple=true
  587:             if (numSections < 3) {
  588:                 document.$formname.$sec_element.size=numSections;
  589:             } else {
  590:                 document.$formname.$sec_element.size=3;
  591:             }
  592:             document.$formname.$sec_element.options[0].selected = false
  593:         }
  594:     }
  595: }
  596: |;
  597:     return $setsections;
  598: }
  599: 
  600: 
  601: sub selectcourse_link {
  602:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  603:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  604:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  605: }
  606: 
  607: sub selectauthor_link {
  608:    my ($form,$udom)=@_;
  609:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  610:           &mt('Select Author').'</a>';
  611: }
  612: 
  613: sub check_uncheck_jscript {
  614:     my $jscript = <<"ENDSCRT";
  615: function checkAll(field) {
  616:     if (field.length > 0) {
  617:         for (i = 0; i < field.length; i++) {
  618:             field[i].checked = true ;
  619:         }
  620:     } else {
  621:         field.checked = true
  622:     }
  623: }
  624:  
  625: function uncheckAll(field) {
  626:     if (field.length > 0) {
  627:         for (i = 0; i < field.length; i++) {
  628:             field[i].checked = false ;
  629:         }
  630:     } else {
  631:         field.checked = false ;
  632:     }
  633: }
  634: ENDSCRT
  635:     return $jscript;
  636: }
  637: 
  638: sub select_timezone {
  639:    my ($name,$selected,$onchange,$includeempty)=@_;
  640:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  641:    if ($includeempty) {
  642:        $output .= '<option value=""';
  643:        if (($selected eq '') || ($selected eq 'local')) {
  644:            $output .= ' selected="selected" ';
  645:        }
  646:        $output .= '> </option>';
  647:    }
  648:    my @timezones = DateTime::TimeZone->all_names;
  649:    foreach my $tzone (@timezones) {
  650:        $output.= '<option value="'.$tzone.'"';
  651:        if ($tzone eq $selected) {
  652:            $output.=' selected="selected"';
  653:        }
  654:        $output.=">$tzone</option>\n";
  655:    }
  656:    $output.="</select>";
  657:    return $output;
  658: }
  659: 
  660: =pod
  661: 
  662: =item * &linked_select_forms(...)
  663: 
  664: linked_select_forms returns a string containing a <script></script> block
  665: and html for two <select> menus.  The select menus will be linked in that
  666: changing the value of the first menu will result in new values being placed
  667: in the second menu.  The values in the select menu will appear in alphabetical
  668: order unless a defined order is provided.
  669: 
  670: linked_select_forms takes the following ordered inputs:
  671: 
  672: =over 4
  673: 
  674: =item * $formname, the name of the <form> tag
  675: 
  676: =item * $middletext, the text which appears between the <select> tags
  677: 
  678: =item * $firstdefault, the default value for the first menu
  679: 
  680: =item * $firstselectname, the name of the first <select> tag
  681: 
  682: =item * $secondselectname, the name of the second <select> tag
  683: 
  684: =item * $hashref, a reference to a hash containing the data for the menus.
  685: 
  686: =item * $menuorder, the order of values in the first menu
  687: 
  688: =back 
  689: 
  690: Below is an example of such a hash.  Only the 'text', 'default', and 
  691: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  692: values for the first select menu.  The text that coincides with the 
  693: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  694: and text for the second menu are given in the hash pointed to by 
  695: $menu{$choice1}->{'select2'}.  
  696: 
  697:  my %menu = ( A1 => { text =>"Choice A1" ,
  698:                        default => "B3",
  699:                        select2 => { 
  700:                            B1 => "Choice B1",
  701:                            B2 => "Choice B2",
  702:                            B3 => "Choice B3",
  703:                            B4 => "Choice B4"
  704:                            },
  705:                        order => ['B4','B3','B1','B2'],
  706:                    },
  707:                A2 => { text =>"Choice A2" ,
  708:                        default => "C2",
  709:                        select2 => { 
  710:                            C1 => "Choice C1",
  711:                            C2 => "Choice C2",
  712:                            C3 => "Choice C3"
  713:                            },
  714:                        order => ['C2','C1','C3'],
  715:                    },
  716:                A3 => { text =>"Choice A3" ,
  717:                        default => "D6",
  718:                        select2 => { 
  719:                            D1 => "Choice D1",
  720:                            D2 => "Choice D2",
  721:                            D3 => "Choice D3",
  722:                            D4 => "Choice D4",
  723:                            D5 => "Choice D5",
  724:                            D6 => "Choice D6",
  725:                            D7 => "Choice D7"
  726:                            },
  727:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  728:                    }
  729:                );
  730: 
  731: =cut
  732: 
  733: sub linked_select_forms {
  734:     my ($formname,
  735:         $middletext,
  736:         $firstdefault,
  737:         $firstselectname,
  738:         $secondselectname, 
  739:         $hashref,
  740:         $menuorder,
  741:         ) = @_;
  742:     my $second = "document.$formname.$secondselectname";
  743:     my $first = "document.$formname.$firstselectname";
  744:     # output the javascript to do the changing
  745:     my $result = '';
  746:     $result.="<script type=\"text/javascript\">\n";
  747:     $result.="var select2data = new Object();\n";
  748:     $" = '","';
  749:     my $debug = '';
  750:     foreach my $s1 (sort(keys(%$hashref))) {
  751:         $result.="select2data.d_$s1 = new Object();\n";        
  752:         $result.="select2data.d_$s1.def = new String('".
  753:             $hashref->{$s1}->{'default'}."');\n";
  754:         $result.="select2data.d_$s1.values = new Array(";
  755:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  756:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  757:             @s2values = @{$hashref->{$s1}->{'order'}};
  758:         }
  759:         $result.="\"@s2values\");\n";
  760:         $result.="select2data.d_$s1.texts = new Array(";        
  761:         my @s2texts;
  762:         foreach my $value (@s2values) {
  763:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  764:         }
  765:         $result.="\"@s2texts\");\n";
  766:     }
  767:     $"=' ';
  768:     $result.= <<"END";
  769: 
  770: function select1_changed() {
  771:     // Determine new choice
  772:     var newvalue = "d_" + $first.value;
  773:     // update select2
  774:     var values     = select2data[newvalue].values;
  775:     var texts      = select2data[newvalue].texts;
  776:     var select2def = select2data[newvalue].def;
  777:     var i;
  778:     // out with the old
  779:     for (i = 0; i < $second.options.length; i++) {
  780:         $second.options[i] = null;
  781:     }
  782:     // in with the nuclear
  783:     for (i=0;i<values.length; i++) {
  784:         $second.options[i] = new Option(values[i]);
  785:         $second.options[i].value = values[i];
  786:         $second.options[i].text = texts[i];
  787:         if (values[i] == select2def) {
  788:             $second.options[i].selected = true;
  789:         }
  790:     }
  791: }
  792: </script>
  793: END
  794:     # output the initial values for the selection lists
  795:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  796:     my @order = sort(keys(%{$hashref}));
  797:     if (ref($menuorder) eq 'ARRAY') {
  798:         @order = @{$menuorder};
  799:     }
  800:     foreach my $value (@order) {
  801:         $result.="    <option value=\"$value\" ";
  802:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  803:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  804:     }
  805:     $result .= "</select>\n";
  806:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  807:     $result .= $middletext;
  808:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  809:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  810:     
  811:     my @secondorder = sort(keys(%select2));
  812:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  813:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  814:     }
  815:     foreach my $value (@secondorder) {
  816:         $result.="    <option value=\"$value\" ";        
  817:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  818:         $result.=">".&mt($select2{$value})."</option>\n";
  819:     }
  820:     $result .= "</select>\n";
  821:     #    return $debug;
  822:     return $result;
  823: }   #  end of sub linked_select_forms {
  824: 
  825: =pod
  826: 
  827: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  828: 
  829: Returns a string corresponding to an HTML link to the given help
  830: $topic, where $topic corresponds to the name of a .tex file in
  831: /home/httpd/html/adm/help/tex, with underscores replaced by
  832: spaces. 
  833: 
  834: $text will optionally be linked to the same topic, allowing you to
  835: link text in addition to the graphic. If you do not want to link
  836: text, but wish to specify one of the later parameters, pass an
  837: empty string. 
  838: 
  839: $stayOnPage is a value that will be interpreted as a boolean. If true,
  840: the link will not open a new window. If false, the link will open
  841: a new window using Javascript. (Default is false.) 
  842: 
  843: $width and $height are optional numerical parameters that will
  844: override the width and height of the popped up window, which may
  845: be useful for certain help topics with big pictures included. 
  846: 
  847: =cut
  848: 
  849: sub help_open_topic {
  850:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  851:     $text = "" if (not defined $text);
  852:     $stayOnPage = 0 if (not defined $stayOnPage);
  853:     if ($env{'browser.interface'} eq 'textual') {
  854: 	$stayOnPage=1;
  855:     }
  856:     $width = 350 if (not defined $width);
  857:     $height = 400 if (not defined $height);
  858:     my $filename = $topic;
  859:     $filename =~ s/ /_/g;
  860: 
  861:     my $template = "";
  862:     my $link;
  863:     
  864:     $topic=~s/\W/\_/g;
  865: 
  866:     if (!$stayOnPage) {
  867: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  868:     } else {
  869: 	$link = "/adm/help/${filename}.hlp";
  870:     }
  871: 
  872:     # Add the text
  873:     if ($text ne "") {
  874: 	$template .= 
  875:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  876:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  877:     }
  878: 
  879:     # Add the graphic
  880:     my $title = &mt('Online Help');
  881:     my $helpicon=&lonhttpdurl("/res/adm/pages/help.png");
  882:     $template .= <<"ENDTEMPLATE";
  883:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  884: ENDTEMPLATE
  885:     if ($text ne '') { $template.='</td></tr></table>' };
  886:     return $template;
  887: 
  888: }
  889: 
  890: # This is a quicky function for Latex cheatsheet editing, since it 
  891: # appears in at least four places
  892: sub helpLatexCheatsheet {
  893:     my $other = shift;
  894:     my $addOther = '';
  895:     if ($other) {
  896: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  897: 						       undef, undef, 600) .
  898: 							   '</td><td>';
  899:     }
  900:     return '<table><tr><td>'.
  901: 	$addOther .
  902: 	&Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  903: 					    undef,undef,600)
  904: 	.'</td><td>'.
  905: 	&Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
  906: 					    undef,undef,600)
  907: 	.'</td></tr></table>';
  908: }
  909: 
  910: sub general_help {
  911:     my $helptopic='Student_Intro';
  912:     if ($env{'request.role'}=~/^(ca|au)/) {
  913: 	$helptopic='Authoring_Intro';
  914:     } elsif ($env{'request.role'}=~/^cc/) {
  915: 	$helptopic='Course_Coordination_Intro';
  916:     }
  917:     return $helptopic;
  918: }
  919: 
  920: sub update_help_link {
  921:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  922:     my $origurl = $ENV{'REQUEST_URI'};
  923:     $origurl=~s|^/~|/priv/|;
  924:     my $timestamp = time;
  925:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  926:         $$datum = &escape($$datum);
  927:     }
  928: 
  929:     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";
  930:     my $output .= <<"ENDOUTPUT";
  931: <script type="text/javascript">
  932: banner_link = '$banner_link';
  933: </script>
  934: ENDOUTPUT
  935:     return $output;
  936: }
  937: 
  938: # now just updates the help link and generates a blue icon
  939: sub help_open_menu {
  940:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
  941: 	= @_;    
  942:     $stayOnPage = 0 if (not defined $stayOnPage);
  943:     # only use pop-up help (stayOnPage == 0)
  944:     # if environment.remote is on (using remote control UI)
  945:     if ($env{'browser.interface'} eq 'textual' ||
  946:     	$env{'environment.remote'} eq 'off' ) {
  947:         $stayOnPage=1;
  948:     }
  949:     my $output;
  950:     if ($component_help) {
  951: 	if (!$text) {
  952: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
  953: 				       $width,$height);
  954: 	} else {
  955: 	    my $help_text;
  956: 	    $help_text=&unescape($topic);
  957: 	    $output='<table><tr><td>'.
  958: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  959: 				 $width,$height).'</td></tr></table>';
  960: 	}
  961:     }
  962:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
  963:     return $output.$banner_link;
  964: }
  965: 
  966: sub top_nav_help {
  967:     my ($text) = @_;
  968:     $text = &mt($text);
  969:     my $stay_on_page = 
  970: 	($env{'browser.interface'}  eq 'textual' ||
  971: 	 $env{'environment.remote'} eq 'off' );
  972:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
  973: 	                     : "javascript:helpMenu('open')";
  974:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
  975: 
  976:     my $title = &mt('Get help');
  977: 
  978:     return <<"END";
  979: $banner_link
  980:  <a href="$link" title="$title">$text</a>
  981: END
  982: }
  983: 
  984: sub help_menu_js {
  985:     my ($text) = @_;
  986: 
  987:     my $stayOnPage = 
  988: 	($env{'browser.interface'}  eq 'textual' ||
  989: 	 $env{'environment.remote'} eq 'off' );
  990: 
  991:     my $width = 620;
  992:     my $height = 600;
  993:     my $helptopic=&general_help();
  994:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
  995:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  996:     my $start_page =
  997:         &Apache::loncommon::start_page('Help Menu', undef,
  998: 				       {'frameset'    => 1,
  999: 					'js_ready'    => 1,
 1000: 					'add_entries' => {
 1001: 					    'border' => '0',
 1002: 					    'rows'   => "110,*",},});
 1003:     my $end_page =
 1004:         &Apache::loncommon::end_page({'frameset' => 1,
 1005: 				      'js_ready' => 1,});
 1006: 
 1007:     my $template .= <<"ENDTEMPLATE";
 1008: <script type="text/javascript">
 1009: // <!-- BEGIN LON-CAPA Internal
 1010: // <![CDATA[
 1011: var banner_link = '';
 1012: function helpMenu(target) {
 1013:     var caller = this;
 1014:     if (target == 'open') {
 1015:         var newWindow = null;
 1016:         try {
 1017:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1018:         }
 1019:         catch(error) {
 1020:             writeHelp(caller);
 1021:             return;
 1022:         }
 1023:         if (newWindow) {
 1024:             caller = newWindow;
 1025:         }
 1026:     }
 1027:     writeHelp(caller);
 1028:     return;
 1029: }
 1030: function writeHelp(caller) {
 1031:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1032:     caller.document.close()
 1033:     caller.focus()
 1034: }
 1035: // ]]>
 1036: // END LON-CAPA Internal -->
 1037: </script>
 1038: ENDTEMPLATE
 1039:     return $template;
 1040: }
 1041: 
 1042: sub help_open_bug {
 1043:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1044:     unless ($env{'user.adv'}) { return ''; }
 1045:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1046:     $text = "" if (not defined $text);
 1047:     $stayOnPage = 0 if (not defined $stayOnPage);
 1048:     if ($env{'browser.interface'} eq 'textual' ||
 1049: 	$env{'environment.remote'} eq 'off' ) {
 1050: 	$stayOnPage=1;
 1051:     }
 1052:     $width = 600 if (not defined $width);
 1053:     $height = 600 if (not defined $height);
 1054: 
 1055:     $topic=~s/\W+/\+/g;
 1056:     my $link='';
 1057:     my $template='';
 1058:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1059: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1060:     if (!$stayOnPage)
 1061:     {
 1062: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1063:     }
 1064:     else
 1065:     {
 1066: 	$link = $url;
 1067:     }
 1068:     # Add the text
 1069:     if ($text ne "")
 1070:     {
 1071: 	$template .= 
 1072:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1073:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1074:     }
 1075: 
 1076:     # Add the graphic
 1077:     my $title = &mt('Report a Bug');
 1078:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1079:     $template .= <<"ENDTEMPLATE";
 1080:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1081: ENDTEMPLATE
 1082:     if ($text ne '') { $template.='</td></tr></table>' };
 1083:     return $template;
 1084: 
 1085: }
 1086: 
 1087: sub help_open_faq {
 1088:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1089:     unless ($env{'user.adv'}) { return ''; }
 1090:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1091:     $text = "" if (not defined $text);
 1092:     $stayOnPage = 0 if (not defined $stayOnPage);
 1093:     if ($env{'browser.interface'} eq 'textual' ||
 1094: 	$env{'environment.remote'} eq 'off' ) {
 1095: 	$stayOnPage=1;
 1096:     }
 1097:     $width = 350 if (not defined $width);
 1098:     $height = 400 if (not defined $height);
 1099: 
 1100:     $topic=~s/\W+/\+/g;
 1101:     my $link='';
 1102:     my $template='';
 1103:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1104:     if (!$stayOnPage)
 1105:     {
 1106: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1107:     }
 1108:     else
 1109:     {
 1110: 	$link = $url;
 1111:     }
 1112: 
 1113:     # Add the text
 1114:     if ($text ne "")
 1115:     {
 1116: 	$template .= 
 1117:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1118:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1119:     }
 1120: 
 1121:     # Add the graphic
 1122:     my $title = &mt('View the FAQ');
 1123:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1124:     $template .= <<"ENDTEMPLATE";
 1125:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1126: ENDTEMPLATE
 1127:     if ($text ne '') { $template.='</td></tr></table>' };
 1128:     return $template;
 1129: 
 1130: }
 1131: 
 1132: ###############################################################
 1133: ###############################################################
 1134: 
 1135: =pod
 1136: 
 1137: =item * &change_content_javascript():
 1138: 
 1139: This and the next function allow you to create small sections of an
 1140: otherwise static HTML page that you can update on the fly with
 1141: Javascript, even in Netscape 4.
 1142: 
 1143: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1144: must be written to the HTML page once. It will prove the Javascript
 1145: function "change(name, content)". Calling the change function with the
 1146: name of the section 
 1147: you want to update, matching the name passed to C<changable_area>, and
 1148: the new content you want to put in there, will put the content into
 1149: that area.
 1150: 
 1151: B<Note>: Netscape 4 only reserves enough space for the changable area
 1152: to contain room for the original contents. You need to "make space"
 1153: for whatever changes you wish to make, and be B<sure> to check your
 1154: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1155: it's adequate for updating a one-line status display, but little more.
 1156: This script will set the space to 100% width, so you only need to
 1157: worry about height in Netscape 4.
 1158: 
 1159: Modern browsers are much less limiting, and if you can commit to the
 1160: user not using Netscape 4, this feature may be used freely with
 1161: pretty much any HTML.
 1162: 
 1163: =cut
 1164: 
 1165: sub change_content_javascript {
 1166:     # If we're on Netscape 4, we need to use Layer-based code
 1167:     if ($env{'browser.type'} eq 'netscape' &&
 1168: 	$env{'browser.version'} =~ /^4\./) {
 1169: 	return (<<NETSCAPE4);
 1170: 	function change(name, content) {
 1171: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1172: 	    doc.open();
 1173: 	    doc.write(content);
 1174: 	    doc.close();
 1175: 	}
 1176: NETSCAPE4
 1177:     } else {
 1178: 	# Otherwise, we need to use semi-standards-compliant code
 1179: 	# (technically, "innerHTML" isn't standard but the equivalent
 1180: 	# is really scary, and every useful browser supports it
 1181: 	return (<<DOMBASED);
 1182: 	function change(name, content) {
 1183: 	    element = document.getElementById(name);
 1184: 	    element.innerHTML = content;
 1185: 	}
 1186: DOMBASED
 1187:     }
 1188: }
 1189: 
 1190: =pod
 1191: 
 1192: =item * &changable_area($name,$origContent):
 1193: 
 1194: This provides a "changable area" that can be modified on the fly via
 1195: the Javascript code provided in C<change_content_javascript>. $name is
 1196: the name you will use to reference the area later; do not repeat the
 1197: same name on a given HTML page more then once. $origContent is what
 1198: the area will originally contain, which can be left blank.
 1199: 
 1200: =cut
 1201: 
 1202: sub changable_area {
 1203:     my ($name, $origContent) = @_;
 1204: 
 1205:     if ($env{'browser.type'} eq 'netscape' &&
 1206: 	$env{'browser.version'} =~ /^4\./) {
 1207: 	# If this is netscape 4, we need to use the Layer tag
 1208: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1209:     } else {
 1210: 	return "<span id='$name'>$origContent</span>";
 1211:     }
 1212: }
 1213: 
 1214: =pod
 1215: 
 1216: =item * &viewport_geometry_js 
 1217: 
 1218: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1219: 
 1220: =cut
 1221: 
 1222: 
 1223: sub viewport_geometry_js { 
 1224:     return <<"GEOMETRY";
 1225: var Geometry = {};
 1226: function init_geometry() {
 1227:     if (Geometry.init) { return };
 1228:     Geometry.init=1;
 1229:     if (window.innerHeight) {
 1230:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1231:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1232:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1233:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1234:     }
 1235:     else if (document.documentElement && document.documentElement.clientHeight) {
 1236:         Geometry.getViewportHeight =
 1237:             function() { return document.documentElement.clientHeight; };
 1238:         Geometry.getViewportWidth =
 1239:             function() { return document.documentElement.clientWidth; };
 1240: 
 1241:         Geometry.getHorizontalScroll =
 1242:             function() { return document.documentElement.scrollLeft; };
 1243:         Geometry.getVerticalScroll =
 1244:             function() { return document.documentElement.scrollTop; };
 1245:     }
 1246:     else if (document.body.clientHeight) {
 1247:         Geometry.getViewportHeight =
 1248:             function() { return document.body.clientHeight; };
 1249:         Geometry.getViewportWidth =
 1250:             function() { return document.body.clientWidth; };
 1251:         Geometry.getHorizontalScroll =
 1252:             function() { return document.body.scrollLeft; };
 1253:         Geometry.getVerticalScroll =
 1254:             function() { return document.body.scrollTop; };
 1255:     }
 1256: }
 1257: 
 1258: GEOMETRY
 1259: }
 1260: 
 1261: =pod
 1262: 
 1263: =item * &viewport_size_js()
 1264: 
 1265: 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. 
 1266: 
 1267: =cut
 1268: 
 1269: sub viewport_size_js {
 1270:     my $geometry = &viewport_geometry_js();
 1271:     return <<"DIMS";
 1272: 
 1273: $geometry
 1274: 
 1275: function getViewportDims(width,height) {
 1276:     init_geometry();
 1277:     width.value = Geometry.getViewportWidth();
 1278:     height.value = Geometry.getViewportHeight();
 1279:     return;
 1280: }
 1281: 
 1282: DIMS
 1283: }
 1284: 
 1285: =pod
 1286: 
 1287: =item * &resize_textarea_js()
 1288: 
 1289: emits the needed javascript to resize a textarea to be as big as possible
 1290: 
 1291: creates a function resize_textrea that takes two IDs first should be
 1292: the id of the element to resize, second should be the id of a div that
 1293: surrounds everything that comes after the textarea, this routine needs
 1294: to be attached to the <body> for the onload and onresize events.
 1295: 
 1296: =back
 1297: 
 1298: =cut
 1299: 
 1300: sub resize_textarea_js {
 1301:     my $geometry = &viewport_geometry_js();
 1302:     return <<"RESIZE";
 1303:     <script type="text/javascript">
 1304: $geometry
 1305: 
 1306: function getX(element) {
 1307:     var x = 0;
 1308:     while (element) {
 1309: 	x += element.offsetLeft;
 1310: 	element = element.offsetParent;
 1311:     }
 1312:     return x;
 1313: }
 1314: function getY(element) {
 1315:     var y = 0;
 1316:     while (element) {
 1317: 	y += element.offsetTop;
 1318: 	element = element.offsetParent;
 1319:     }
 1320:     return y;
 1321: }
 1322: 
 1323: 
 1324: function resize_textarea(textarea_id,bottom_id) {
 1325:     init_geometry();
 1326:     var textarea        = document.getElementById(textarea_id);
 1327:     //alert(textarea);
 1328: 
 1329:     var textarea_top    = getY(textarea);
 1330:     var textarea_height = textarea.offsetHeight;
 1331:     var bottom          = document.getElementById(bottom_id);
 1332:     var bottom_top      = getY(bottom);
 1333:     var bottom_height   = bottom.offsetHeight;
 1334:     var window_height   = Geometry.getViewportHeight();
 1335:     var fudge           = 23;
 1336:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1337:     if (new_height < 300) {
 1338: 	new_height = 300;
 1339:     }
 1340:     textarea.style.height=new_height+'px';
 1341: }
 1342: </script>
 1343: RESIZE
 1344: 
 1345: }
 1346: 
 1347: =pod
 1348: 
 1349: =head1 Excel and CSV file utility routines
 1350: 
 1351: =over 4
 1352: 
 1353: =cut
 1354: 
 1355: ###############################################################
 1356: ###############################################################
 1357: 
 1358: =pod
 1359: 
 1360: =item * &csv_translate($text) 
 1361: 
 1362: Translate $text to allow it to be output as a 'comma separated values' 
 1363: format.
 1364: 
 1365: =cut
 1366: 
 1367: ###############################################################
 1368: ###############################################################
 1369: sub csv_translate {
 1370:     my $text = shift;
 1371:     $text =~ s/\"/\"\"/g;
 1372:     $text =~ s/\n/ /g;
 1373:     return $text;
 1374: }
 1375: 
 1376: ###############################################################
 1377: ###############################################################
 1378: 
 1379: =pod
 1380: 
 1381: =item * &define_excel_formats()
 1382: 
 1383: Define some commonly used Excel cell formats.
 1384: 
 1385: Currently supported formats:
 1386: 
 1387: =over 4
 1388: 
 1389: =item header
 1390: 
 1391: =item bold
 1392: 
 1393: =item h1
 1394: 
 1395: =item h2
 1396: 
 1397: =item h3
 1398: 
 1399: =item h4
 1400: 
 1401: =item i
 1402: 
 1403: =item date
 1404: 
 1405: =back
 1406: 
 1407: Inputs: $workbook
 1408: 
 1409: Returns: $format, a hash reference.
 1410: 
 1411: =cut
 1412: 
 1413: ###############################################################
 1414: ###############################################################
 1415: sub define_excel_formats {
 1416:     my ($workbook) = @_;
 1417:     my $format;
 1418:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1419:                                                 bottom    => 1,
 1420:                                                 align     => 'center');
 1421:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1422:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1423:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1424:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1425:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1426:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1427:     $format->{'date'} = $workbook->add_format(num_format=>
 1428:                                             'mm/dd/yyyy hh:mm:ss');
 1429:     return $format;
 1430: }
 1431: 
 1432: ###############################################################
 1433: ###############################################################
 1434: 
 1435: =pod
 1436: 
 1437: =item * &create_workbook()
 1438: 
 1439: Create an Excel worksheet.  If it fails, output message on the
 1440: request object and return undefs.
 1441: 
 1442: Inputs: Apache request object
 1443: 
 1444: Returns (undef) on failure, 
 1445:     Excel worksheet object, scalar with filename, and formats 
 1446:     from &Apache::loncommon::define_excel_formats on success
 1447: 
 1448: =cut
 1449: 
 1450: ###############################################################
 1451: ###############################################################
 1452: sub create_workbook {
 1453:     my ($r) = @_;
 1454:         #
 1455:     # Create the excel spreadsheet
 1456:     my $filename = '/prtspool/'.
 1457:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1458:         time.'_'.rand(1000000000).'.xls';
 1459:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1460:     if (! defined($workbook)) {
 1461:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1462:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1463:                             "This error has been logged.  ".
 1464:                             "Please alert your LON-CAPA administrator").
 1465:                   '</p>');
 1466:         return (undef);
 1467:     }
 1468:     #
 1469:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1470:     #
 1471:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1472:     return ($workbook,$filename,$format);
 1473: }
 1474: 
 1475: ###############################################################
 1476: ###############################################################
 1477: 
 1478: =pod
 1479: 
 1480: =item * &create_text_file()
 1481: 
 1482: Create a file to write to and eventually make available to the user.
 1483: If file creation fails, outputs an error message on the request object and 
 1484: return undefs.
 1485: 
 1486: Inputs: Apache request object, and file suffix
 1487: 
 1488: Returns (undef) on failure, 
 1489:     Filehandle and filename on success.
 1490: 
 1491: =cut
 1492: 
 1493: ###############################################################
 1494: ###############################################################
 1495: sub create_text_file {
 1496:     my ($r,$suffix) = @_;
 1497:     if (! defined($suffix)) { $suffix = 'txt'; };
 1498:     my $fh;
 1499:     my $filename = '/prtspool/'.
 1500:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1501:         time.'_'.rand(1000000000).'.'.$suffix;
 1502:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1503:     if (! defined($fh)) {
 1504:         $r->log_error("Couldn't open $filename for output $!");
 1505:         $r->print("Problems occured in creating the output file.  ".
 1506:                   "This error has been logged.  ".
 1507:                   "Please alert your LON-CAPA administrator.");
 1508:     }
 1509:     return ($fh,$filename)
 1510: }
 1511: 
 1512: 
 1513: =pod 
 1514: 
 1515: =back
 1516: 
 1517: =cut
 1518: 
 1519: ###############################################################
 1520: ##        Home server <option> list generating code          ##
 1521: ###############################################################
 1522: 
 1523: # ------------------------------------------
 1524: 
 1525: sub domain_select {
 1526:     my ($name,$value,$multiple)=@_;
 1527:     my %domains=map { 
 1528: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1529:     } &Apache::lonnet::all_domains();
 1530:     if ($multiple) {
 1531: 	$domains{''}=&mt('Any domain');
 1532: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1533: 	return &multiple_select_form($name,$value,4,\%domains);
 1534:     } else {
 1535: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1536: 	return &select_form($name,$value,%domains);
 1537:     }
 1538: }
 1539: 
 1540: #-------------------------------------------
 1541: 
 1542: =pod
 1543: 
 1544: =head1 Routines for form select boxes
 1545: 
 1546: =over 4
 1547: 
 1548: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1549: 
 1550: Returns a string containing a <select> element int multiple mode
 1551: 
 1552: 
 1553: Args:
 1554:   $name - name of the <select> element
 1555:   $value - scalar or array ref of values that should already be selected
 1556:   $size - number of rows long the select element is
 1557:   $hash - the elements should be 'option' => 'shown text'
 1558:           (shown text should already have been &mt())
 1559:   $order - (optional) array ref of the order to show the elements in
 1560: 
 1561: =cut
 1562: 
 1563: #-------------------------------------------
 1564: sub multiple_select_form {
 1565:     my ($name,$value,$size,$hash,$order)=@_;
 1566:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1567:     my $output='';
 1568:     if (! defined($size)) {
 1569:         $size = 4;
 1570:         if (scalar(keys(%$hash))<4) {
 1571:             $size = scalar(keys(%$hash));
 1572:         }
 1573:     }
 1574:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1575:     my @order;
 1576:     if (ref($order) eq 'ARRAY')  {
 1577:         @order = @{$order};
 1578:     } else {
 1579:         @order = sort(keys(%$hash));
 1580:     }
 1581:     if (exists($$hash{'select_form_order'})) {
 1582:         @order = @{$$hash{'select_form_order'}};
 1583:     }
 1584:         
 1585:     foreach my $key (@order) {
 1586:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1587:         $output.='selected="selected" ' if ($selected{$key});
 1588:         $output.='>'.$hash->{$key}."</option>\n";
 1589:     }
 1590:     $output.="</select>\n";
 1591:     return $output;
 1592: }
 1593: 
 1594: #-------------------------------------------
 1595: 
 1596: =pod
 1597: 
 1598: =item * &select_form($defdom,$name,%hash)
 1599: 
 1600: Returns a string containing a <select name='$name' size='1'> form to 
 1601: allow a user to select options from a hash option_name => displayed text.  
 1602: See lonrights.pm for an example invocation and use.
 1603: 
 1604: =cut
 1605: 
 1606: #-------------------------------------------
 1607: sub select_form {
 1608:     my ($def,$name,%hash) = @_;
 1609:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1610:     my @keys;
 1611:     if (exists($hash{'select_form_order'})) {
 1612: 	@keys=@{$hash{'select_form_order'}};
 1613:     } else {
 1614: 	@keys=sort(keys(%hash));
 1615:     }
 1616:     foreach my $key (@keys) {
 1617:         $selectform.=
 1618: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1619:             ($key eq $def ? 'selected="selected" ' : '').
 1620:                 ">".&mt($hash{$key})."</option>\n";
 1621:     }
 1622:     $selectform.="</select>";
 1623:     return $selectform;
 1624: }
 1625: 
 1626: # For display filters
 1627: 
 1628: sub display_filter {
 1629:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1630:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1631:     return '<nobr><label>'.&mt('Records [_1]',
 1632: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1633: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1634: 	   '</label></nobr> <nobr>'.
 1635:            &mt('Filter [_1]',
 1636: 	   &select_form($env{'form.displayfilter'},
 1637: 			'displayfilter',
 1638: 			('currentfolder' => 'Current folder/page',
 1639: 			 'containing' => 'Containing phrase',
 1640: 			 'none' => 'None'))).
 1641: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
 1642: }
 1643: 
 1644: sub gradeleveldescription {
 1645:     my $gradelevel=shift;
 1646:     my %gradelevels=(0 => 'Not specified',
 1647: 		     1 => 'Grade 1',
 1648: 		     2 => 'Grade 2',
 1649: 		     3 => 'Grade 3',
 1650: 		     4 => 'Grade 4',
 1651: 		     5 => 'Grade 5',
 1652: 		     6 => 'Grade 6',
 1653: 		     7 => 'Grade 7',
 1654: 		     8 => 'Grade 8',
 1655: 		     9 => 'Grade 9',
 1656: 		     10 => 'Grade 10',
 1657: 		     11 => 'Grade 11',
 1658: 		     12 => 'Grade 12',
 1659: 		     13 => 'Grade 13',
 1660: 		     14 => '100 Level',
 1661: 		     15 => '200 Level',
 1662: 		     16 => '300 Level',
 1663: 		     17 => '400 Level',
 1664: 		     18 => 'Graduate Level');
 1665:     return &mt($gradelevels{$gradelevel});
 1666: }
 1667: 
 1668: sub select_level_form {
 1669:     my ($deflevel,$name)=@_;
 1670:     unless ($deflevel) { $deflevel=0; }
 1671:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1672:     for (my $i=0; $i<=18; $i++) {
 1673:         $selectform.="<option value=\"$i\" ".
 1674:             ($i==$deflevel ? 'selected="selected" ' : '').
 1675:                 ">".&gradeleveldescription($i)."</option>\n";
 1676:     }
 1677:     $selectform.="</select>";
 1678:     return $selectform;
 1679: }
 1680: 
 1681: #-------------------------------------------
 1682: 
 1683: =pod
 1684: 
 1685: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
 1686: 
 1687: Returns a string containing a <select name='$name' size='1'> form to 
 1688: allow a user to select the domain to preform an operation in.  
 1689: See loncreateuser.pm for an example invocation and use.
 1690: 
 1691: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1692: selected");
 1693: 
 1694: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
 1695: 
 1696: =cut
 1697: 
 1698: #-------------------------------------------
 1699: sub select_dom_form {
 1700:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
 1701:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1702:     if ($includeempty) { @domains=('',@domains); }
 1703:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1704:     foreach my $dom (@domains) {
 1705:         $selectdomain.="<option value=\"$dom\" ".
 1706:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1707:         if ($showdomdesc) {
 1708:             if ($dom ne '') {
 1709:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1710:                 if ($domdesc ne '') {
 1711:                     $selectdomain .= ' ('.$domdesc.')';
 1712:                 }
 1713:             } 
 1714:         }
 1715:         $selectdomain .= "</option>\n";
 1716:     }
 1717:     $selectdomain.="</select>";
 1718:     return $selectdomain;
 1719: }
 1720: 
 1721: #-------------------------------------------
 1722: 
 1723: =pod
 1724: 
 1725: =item * &home_server_form_item($domain,$name,$defaultflag)
 1726: 
 1727: input: 4 arguments (two required, two optional) - 
 1728:     $domain - domain of new user
 1729:     $name - name of form element
 1730:     $default - Value of 'default' causes a default item to be first 
 1731:                             option, and selected by default. 
 1732:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1733:                             if 1 server found, or default, if 0 found.
 1734: output: returns 2 items: 
 1735: (a) form element which contains either:
 1736:    (i) <select name="$name">
 1737:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1738:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1739:        </select>
 1740:        form item if there are multiple library servers in $domain, or
 1741:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1742:        if there is only one library server in $domain.
 1743: 
 1744: (b) number of library servers found.
 1745: 
 1746: See loncreateuser.pm for example of use.
 1747: 
 1748: =cut
 1749: 
 1750: #-------------------------------------------
 1751: sub home_server_form_item {
 1752:     my ($domain,$name,$default,$hide) = @_;
 1753:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1754:     my $result;
 1755:     my $numlib = keys(%servers);
 1756:     if ($numlib > 1) {
 1757:         $result .= '<select name="'.$name.'" />'."\n";
 1758:         if ($default) {
 1759:             $result .= '<option value="default" selected>'.&mt('default').
 1760:                        '</option>'."\n";
 1761:         }
 1762:         foreach my $hostid (sort(keys(%servers))) {
 1763:             $result.= '<option value="'.$hostid.'">'.
 1764: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1765:         }
 1766:         $result .= '</select>'."\n";
 1767:     } elsif ($numlib == 1) {
 1768:         my $hostid;
 1769:         foreach my $item (keys(%servers)) {
 1770:             $hostid = $item;
 1771:         }
 1772:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1773:                    $hostid.'" />';
 1774:                    if (!$hide) {
 1775:                        $result .= $hostid.' '.$servers{$hostid};
 1776:                    }
 1777:                    $result .= "\n";
 1778:     } elsif ($default) {
 1779:         $result .= '<input type="hidden" name="'.$name.
 1780:                    '" value="default" />';
 1781:                    if (!$hide) {
 1782:                        $result .= &mt('default');
 1783:                    }
 1784:                    $result .= "\n";
 1785:     }
 1786:     return ($result,$numlib);
 1787: }
 1788: 
 1789: =pod
 1790: 
 1791: =back 
 1792: 
 1793: =cut
 1794: 
 1795: ###############################################################
 1796: ##                  Decoding User Agent                      ##
 1797: ###############################################################
 1798: 
 1799: =pod
 1800: 
 1801: =head1 Decoding the User Agent
 1802: 
 1803: =over 4
 1804: 
 1805: =item * &decode_user_agent()
 1806: 
 1807: Inputs: $r
 1808: 
 1809: Outputs:
 1810: 
 1811: =over 4
 1812: 
 1813: =item * $httpbrowser
 1814: 
 1815: =item * $clientbrowser
 1816: 
 1817: =item * $clientversion
 1818: 
 1819: =item * $clientmathml
 1820: 
 1821: =item * $clientunicode
 1822: 
 1823: =item * $clientos
 1824: 
 1825: =back
 1826: 
 1827: =back 
 1828: 
 1829: =cut
 1830: 
 1831: ###############################################################
 1832: ###############################################################
 1833: sub decode_user_agent {
 1834:     my ($r)=@_;
 1835:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1836:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1837:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1838:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1839:     my $clientbrowser='unknown';
 1840:     my $clientversion='0';
 1841:     my $clientmathml='';
 1842:     my $clientunicode='0';
 1843:     for (my $i=0;$i<=$#browsertype;$i++) {
 1844:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1845: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1846: 	    $clientbrowser=$bname;
 1847:             $httpbrowser=~/$vreg/i;
 1848: 	    $clientversion=$1;
 1849:             $clientmathml=($clientversion>=$minv);
 1850:             $clientunicode=($clientversion>=$univ);
 1851: 	}
 1852:     }
 1853:     my $clientos='unknown';
 1854:     if (($httpbrowser=~/linux/i) ||
 1855:         ($httpbrowser=~/unix/i) ||
 1856:         ($httpbrowser=~/ux/i) ||
 1857:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1858:     if (($httpbrowser=~/vax/i) ||
 1859:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1860:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1861:     if (($httpbrowser=~/mac/i) ||
 1862:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1863:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1864:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1865:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1866:             $clientunicode,$clientos,);
 1867: }
 1868: 
 1869: ###############################################################
 1870: ##    Authentication changing form generation subroutines    ##
 1871: ###############################################################
 1872: ##
 1873: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1874: ## hash, and have reasonable default values.
 1875: ##
 1876: ##    formname = the name given in the <form> tag.
 1877: #-------------------------------------------
 1878: 
 1879: =pod
 1880: 
 1881: =head1 Authentication Routines
 1882: 
 1883: =over 4
 1884: 
 1885: =item * &authform_xxxxxx()
 1886: 
 1887: The authform_xxxxxx subroutines provide javascript and html forms which 
 1888: handle some of the conveniences required for authentication forms.  
 1889: This is not an optimal method, but it works.  
 1890: 
 1891: =over 4
 1892: 
 1893: =item * authform_header
 1894: 
 1895: =item * authform_authorwarning
 1896: 
 1897: =item * authform_nochange
 1898: 
 1899: =item * authform_kerberos
 1900: 
 1901: =item * authform_internal
 1902: 
 1903: =item * authform_filesystem
 1904: 
 1905: =back
 1906: 
 1907: See loncreateuser.pm for invocation and use examples.
 1908: 
 1909: =cut
 1910: 
 1911: #-------------------------------------------
 1912: sub authform_header{  
 1913:     my %in = (
 1914:         formname => 'cu',
 1915:         kerb_def_dom => '',
 1916:         @_,
 1917:     );
 1918:     $in{'formname'} = 'document.' . $in{'formname'};
 1919:     my $result='';
 1920: 
 1921: #---------------------------------------------- Code for upper case translation
 1922:     my $Javascript_toUpperCase;
 1923:     unless ($in{kerb_def_dom}) {
 1924:         $Javascript_toUpperCase =<<"END";
 1925:         switch (choice) {
 1926:            case 'krb': currentform.elements[choicearg].value =
 1927:                currentform.elements[choicearg].value.toUpperCase();
 1928:                break;
 1929:            default:
 1930:         }
 1931: END
 1932:     } else {
 1933:         $Javascript_toUpperCase = "";
 1934:     }
 1935: 
 1936:     my $radioval = "'nochange'";
 1937:     if (defined($in{'curr_authtype'})) {
 1938:         if ($in{'curr_authtype'} ne '') {
 1939:             $radioval = "'".$in{'curr_authtype'}."arg'";
 1940:         }
 1941:     }
 1942:     my $argfield = 'null';
 1943:     if (defined($in{'mode'})) {
 1944:         if ($in{'mode'} eq 'modifycourse')  {
 1945:             if (defined($in{'curr_autharg'})) {
 1946:                 if ($in{'curr_autharg'} ne '') {
 1947:                     $argfield = "'$in{'curr_autharg'}'";
 1948:                 }
 1949:             }
 1950:         }
 1951:     }
 1952: 
 1953:     $result.=<<"END";
 1954: var current = new Object();
 1955: current.radiovalue = $radioval;
 1956: current.argfield = $argfield;
 1957: 
 1958: function changed_radio(choice,currentform) {
 1959:     var choicearg = choice + 'arg';
 1960:     // If a radio button in changed, we need to change the argfield
 1961:     if (current.radiovalue != choice) {
 1962:         current.radiovalue = choice;
 1963:         if (current.argfield != null) {
 1964:             currentform.elements[current.argfield].value = '';
 1965:         }
 1966:         if (choice == 'nochange') {
 1967:             current.argfield = null;
 1968:         } else {
 1969:             current.argfield = choicearg;
 1970:             switch(choice) {
 1971:                 case 'krb': 
 1972:                     currentform.elements[current.argfield].value = 
 1973:                         "$in{'kerb_def_dom'}";
 1974:                 break;
 1975:               default:
 1976:                 break;
 1977:             }
 1978:         }
 1979:     }
 1980:     return;
 1981: }
 1982: 
 1983: function changed_text(choice,currentform) {
 1984:     var choicearg = choice + 'arg';
 1985:     if (currentform.elements[choicearg].value !='') {
 1986:         $Javascript_toUpperCase
 1987:         // clear old field
 1988:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1989:             currentform.elements[current.argfield].value = '';
 1990:         }
 1991:         current.argfield = choicearg;
 1992:     }
 1993:     set_auth_radio_buttons(choice,currentform);
 1994:     return;
 1995: }
 1996: 
 1997: function set_auth_radio_buttons(newvalue,currentform) {
 1998:     var i=0;
 1999:     while (i < currentform.login.length) {
 2000:         if (currentform.login[i].value == newvalue) { break; }
 2001:         i++;
 2002:     }
 2003:     if (i == currentform.login.length) {
 2004:         return;
 2005:     }
 2006:     current.radiovalue = newvalue;
 2007:     currentform.login[i].checked = true;
 2008:     return;
 2009: }
 2010: END
 2011:     return $result;
 2012: }
 2013: 
 2014: sub authform_authorwarning{
 2015:     my $result='';
 2016:     $result='<i>'.
 2017:         &mt('As a general rule, only authors or co-authors should be '.
 2018:             'filesystem authenticated '.
 2019:             '(which allows access to the server filesystem).')."</i>\n";
 2020:     return $result;
 2021: }
 2022: 
 2023: sub authform_nochange{  
 2024:     my %in = (
 2025:               formname => 'document.cu',
 2026:               kerb_def_dom => 'MSU.EDU',
 2027:               @_,
 2028:           );
 2029:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2030:     my $result;
 2031:     if (keys(%can_assign) == 0) {
 2032:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2033:     } else {
 2034:         $result = '<label>'.&mt('[_1] Do not change login data',
 2035:                   '<input type="radio" name="login" value="nochange" '.
 2036:                   'checked="checked" onclick="'.
 2037:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2038: 	    '</label>';
 2039:     }
 2040:     return $result;
 2041: }
 2042: 
 2043: sub authform_kerberos {
 2044:     my %in = (
 2045:               formname => 'document.cu',
 2046:               kerb_def_dom => 'MSU.EDU',
 2047:               kerb_def_auth => 'krb4',
 2048:               @_,
 2049:               );
 2050:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2051:         $autharg,$jscall);
 2052:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2053:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2054:        $check5 = ' checked="on"';
 2055:     } else {
 2056:        $check4 = ' checked="on"';
 2057:     }
 2058:     $krbarg = $in{'kerb_def_dom'};
 2059:     if (defined($in{'curr_authtype'})) {
 2060:         if ($in{'curr_authtype'} eq 'krb') {
 2061:             $krbcheck = ' checked="on"';
 2062:             if (defined($in{'mode'})) {
 2063:                 if ($in{'mode'} eq 'modifyuser') {
 2064:                     $krbcheck = '';
 2065:                 }
 2066:             }
 2067:             if (defined($in{'curr_kerb_ver'})) {
 2068:                 if ($in{'curr_krb_ver'} eq '5') {
 2069:                     $check5 = ' checked="on"';
 2070:                     $check4 = '';
 2071:                 } else {
 2072:                     $check4 = ' checked="on"';
 2073:                     $check5 = '';
 2074:                 }
 2075:             }
 2076:             if (defined($in{'curr_autharg'})) {
 2077:                 $krbarg = $in{'curr_autharg'};
 2078:             }
 2079:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2080:                 if (defined($in{'curr_autharg'})) {
 2081:                     $result = 
 2082:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2083:         $in{'curr_autharg'},$krbver);
 2084:                 } else {
 2085:                     $result =
 2086:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2087:                 }
 2088:                 return $result; 
 2089:             }
 2090:         }
 2091:     } else {
 2092:         if ($authnum == 1) {
 2093:             $authtype = '<input type="hidden" name="login" value="krb">';
 2094:         }
 2095:     }
 2096:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2097:         return;
 2098:     } elsif ($authtype eq '') {
 2099:         if (defined($in{'mode'})) {
 2100:             if ($in{'mode'} eq 'modifycourse') {
 2101:                 if ($authnum == 1) {
 2102:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2103:                 }
 2104:             }
 2105:         }
 2106:     }
 2107:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2108:     if ($authtype eq '') {
 2109:         $authtype = '<input type="radio" name="login" value="krb" '.
 2110:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2111:                     $krbcheck.' />';
 2112:     }
 2113:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2114:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2115:          $in{'curr_authtype'} eq 'krb5') ||
 2116:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2117:          $in{'curr_authtype'} eq 'krb4')) {
 2118:         $result .= &mt
 2119:         ('[_1] Kerberos authenticated with domain [_2] '.
 2120:          '[_3] Version 4 [_4] Version 5 [_5]',
 2121:          '<label>'.$authtype,
 2122:          '</label><input type="text" size="10" name="krbarg" '.
 2123:              'value="'.$krbarg.'" '.
 2124:              'onchange="'.$jscall.'" />',
 2125:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2126:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2127: 	 '</label>');
 2128:     } elsif ($can_assign{'krb4'}) {
 2129:         $result .= &mt
 2130:         ('[_1] Kerberos authenticated with domain [_2] '.
 2131:          '[_3] Version 4 [_4]',
 2132:          '<label>'.$authtype,
 2133:          '</label><input type="text" size="10" name="krbarg" '.
 2134:              'value="'.$krbarg.'" '.
 2135:              'onchange="'.$jscall.'" />',
 2136:          '<label><input type="hidden" name="krbver" value="4" />',
 2137:          '</label>');
 2138:     } elsif ($can_assign{'krb5'}) {
 2139:         $result .= &mt
 2140:         ('[_1] Kerberos authenticated with domain [_2] '.
 2141:          '[_3] Version 5 [_4]',
 2142:          '<label>'.$authtype,
 2143:          '</label><input type="text" size="10" name="krbarg" '.
 2144:              'value="'.$krbarg.'" '.
 2145:              'onchange="'.$jscall.'" />',
 2146:          '<label><input type="hidden" name="krbver" value="5" />',
 2147:          '</label>');
 2148:     }
 2149:     return $result;
 2150: }
 2151: 
 2152: sub authform_internal{  
 2153:     my %in = (
 2154:                 formname => 'document.cu',
 2155:                 kerb_def_dom => 'MSU.EDU',
 2156:                 @_,
 2157:                 );
 2158:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2159:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2160:     if (defined($in{'curr_authtype'})) {
 2161:         if ($in{'curr_authtype'} eq 'int') {
 2162:             if ($can_assign{'int'}) {
 2163:                 $intcheck = 'checked="on" ';
 2164:                 if (defined($in{'mode'})) {
 2165:                     if ($in{'mode'} eq 'modifyuser') {
 2166:                         $intcheck = '';
 2167:                     }
 2168:                 }
 2169:                 if (defined($in{'curr_autharg'})) {
 2170:                     $intarg = $in{'curr_autharg'};
 2171:                 }
 2172:             } else {
 2173:                 $result = &mt('Currently internally authenticated.');
 2174:                 return $result;
 2175:             }
 2176:         }
 2177:     } else {
 2178:         if ($authnum == 1) {
 2179:             $authtype = '<input type="hidden" name="login" value="int">';
 2180:         }
 2181:     }
 2182:     if (!$can_assign{'int'}) {
 2183:         return;
 2184:     } elsif ($authtype eq '') {
 2185:         if (defined($in{'mode'})) {
 2186:             if ($in{'mode'} eq 'modifycourse') {
 2187:                 if ($authnum == 1) {
 2188:                     $authtype = '<input type="hidden" name="login" value="int">';
 2189:                 }
 2190:             }
 2191:         }
 2192:     }
 2193:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2194:     if ($authtype eq '') {
 2195:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2196:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2197:     }
 2198:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2199:                $intarg.'" onchange="'.$jscall.'" />';
 2200:     $result = &mt
 2201:         ('[_1] Internally authenticated (with initial password [_2])',
 2202:          '<label>'.$authtype,'</label>'.$autharg);
 2203:     $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>';
 2204:     return $result;
 2205: }
 2206: 
 2207: sub authform_local{  
 2208:     my %in = (
 2209:               formname => 'document.cu',
 2210:               kerb_def_dom => 'MSU.EDU',
 2211:               @_,
 2212:               );
 2213:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2214:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2215:     if (defined($in{'curr_authtype'})) {
 2216:         if ($in{'curr_authtype'} eq 'loc') {
 2217:             if ($can_assign{'loc'}) {
 2218:                 $loccheck = 'checked="on" ';
 2219:                 if (defined($in{'mode'})) {
 2220:                     if ($in{'mode'} eq 'modifyuser') {
 2221:                         $loccheck = '';
 2222:                     }
 2223:                 }
 2224:                 if (defined($in{'curr_autharg'})) {
 2225:                     $locarg = $in{'curr_autharg'};
 2226:                 }
 2227:             } else {
 2228:                 $result = &mt('Currently using local (institutional) authentication.');
 2229:                 return $result;
 2230:             }
 2231:         }
 2232:     } else {
 2233:         if ($authnum == 1) {
 2234:             $authtype = '<input type="hidden" name="login" value="loc">';
 2235:         }
 2236:     }
 2237:     if (!$can_assign{'loc'}) {
 2238:         return;
 2239:     } elsif ($authtype eq '') {
 2240:         if (defined($in{'mode'})) {
 2241:             if ($in{'mode'} eq 'modifycourse') {
 2242:                 if ($authnum == 1) {
 2243:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2244:                 }
 2245:             }
 2246:         }
 2247:     }
 2248:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2249:     if ($authtype eq '') {
 2250:         $authtype = '<input type="radio" name="login" value="loc" '.
 2251:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2252:                     $jscall.'" />';
 2253:     }
 2254:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2255:                $locarg.'" onchange="'.$jscall.'" />';
 2256:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2257:                   '<label>'.$authtype,'</label>'.$autharg);
 2258:     return $result;
 2259: }
 2260: 
 2261: sub authform_filesystem{  
 2262:     my %in = (
 2263:               formname => 'document.cu',
 2264:               kerb_def_dom => 'MSU.EDU',
 2265:               @_,
 2266:               );
 2267:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2268:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2269:     if (defined($in{'curr_authtype'})) {
 2270:         if ($in{'curr_authtype'} eq 'fsys') {
 2271:             if ($can_assign{'fsys'}) {
 2272:                 $fsyscheck = 'checked="on" ';
 2273:                 if (defined($in{'mode'})) {
 2274:                     if ($in{'mode'} eq 'modifyuser') {
 2275:                         $fsyscheck = '';
 2276:                     }
 2277:                 }
 2278:             } else {
 2279:                 $result = &mt('Currently Filesystem Authenticated.');
 2280:                 return $result;
 2281:             }           
 2282:         }
 2283:     } else {
 2284:         if ($authnum == 1) {
 2285:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2286:         }
 2287:     }
 2288:     if (!$can_assign{'fsys'}) {
 2289:         return;
 2290:     } elsif ($authtype eq '') {
 2291:         if (defined($in{'mode'})) {
 2292:             if ($in{'mode'} eq 'modifycourse') {
 2293:                 if ($authnum == 1) {
 2294:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2295:                 }
 2296:             }
 2297:         }
 2298:     }
 2299:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2300:     if ($authtype eq '') {
 2301:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2302:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2303:                     $jscall.'" />';
 2304:     }
 2305:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2306:                ' onchange="'.$jscall.'" />';
 2307:     $result = &mt
 2308:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2309:          '<label><input type="radio" name="login" value="fsys" '.
 2310:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2311:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2312:                   'onchange="'.$jscall.'" />');
 2313:     return $result;
 2314: }
 2315: 
 2316: sub get_assignable_auth {
 2317:     my ($dom) = @_;
 2318:     if ($dom eq '') {
 2319:         $dom = $env{'request.role.domain'};
 2320:     }
 2321:     my %can_assign = (
 2322:                           krb4 => 1,
 2323:                           krb5 => 1,
 2324:                           int  => 1,
 2325:                           loc  => 1,
 2326:                      );
 2327:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2328:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2329:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2330:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2331:             my $context;
 2332:             if ($env{'request.role'} =~ /^au/) {
 2333:                 $context = 'author';
 2334:             } elsif ($env{'request.role'} =~ /^dc/) {
 2335:                 $context = 'domain';
 2336:             } elsif ($env{'request.course.id'}) {
 2337:                 $context = 'course';
 2338:             }
 2339:             if ($context) {
 2340:                 if (ref($authhash->{$context}) eq 'HASH') {
 2341:                    %can_assign = %{$authhash->{$context}}; 
 2342:                 }
 2343:             }
 2344:         }
 2345:     }
 2346:     my $authnum = 0;
 2347:     foreach my $key (keys(%can_assign)) {
 2348:         if ($can_assign{$key}) {
 2349:             $authnum ++;
 2350:         }
 2351:     }
 2352:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2353:         $authnum --;
 2354:     }
 2355:     return ($authnum,%can_assign);
 2356: }
 2357: 
 2358: ###############################################################
 2359: ##    Get Kerberos Defaults for Domain                 ##
 2360: ###############################################################
 2361: ##
 2362: ## Returns default kerberos version and an associated argument
 2363: ## as listed in file domain.tab. If not listed, provides
 2364: ## appropriate default domain and kerberos version.
 2365: ##
 2366: #-------------------------------------------
 2367: 
 2368: =pod
 2369: 
 2370: =item * &get_kerberos_defaults()
 2371: 
 2372: get_kerberos_defaults($target_domain) returns the default kerberos
 2373: version and domain. If not found, it defaults to version 4 and the 
 2374: domain of the server.
 2375: 
 2376: =over 4
 2377: 
 2378: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2379: 
 2380: =back
 2381: 
 2382: =back
 2383: 
 2384: =cut
 2385: 
 2386: #-------------------------------------------
 2387: sub get_kerberos_defaults {
 2388:     my $domain=shift;
 2389:     my ($krbdef,$krbdefdom);
 2390:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2391:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2392:         $krbdef = $domdefaults{'auth_def'};
 2393:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2394:     } else {
 2395:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2396:         my $krbdefdom=$1;
 2397:         $krbdefdom=~tr/a-z/A-Z/;
 2398:         $krbdef = "krb4";
 2399:     }
 2400:     return ($krbdef,$krbdefdom);
 2401: }
 2402: 
 2403: 
 2404: ###############################################################
 2405: ##                Thesaurus Functions                        ##
 2406: ###############################################################
 2407: 
 2408: =pod
 2409: 
 2410: =head1 Thesaurus Functions
 2411: 
 2412: =over 4
 2413: 
 2414: =item * &initialize_keywords()
 2415: 
 2416: Initializes the package variable %Keywords if it is empty.  Uses the
 2417: package variable $thesaurus_db_file.
 2418: 
 2419: =cut
 2420: 
 2421: ###################################################
 2422: 
 2423: sub initialize_keywords {
 2424:     return 1 if (scalar keys(%Keywords));
 2425:     # If we are here, %Keywords is empty, so fill it up
 2426:     #   Make sure the file we need exists...
 2427:     if (! -e $thesaurus_db_file) {
 2428:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2429:                                  " failed because it does not exist");
 2430:         return 0;
 2431:     }
 2432:     #   Set up the hash as a database
 2433:     my %thesaurus_db;
 2434:     if (! tie(%thesaurus_db,'GDBM_File',
 2435:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2436:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2437:                                  $thesaurus_db_file);
 2438:         return 0;
 2439:     } 
 2440:     #  Get the average number of appearances of a word.
 2441:     my $avecount = $thesaurus_db{'average.count'};
 2442:     #  Put keywords (those that appear > average) into %Keywords
 2443:     while (my ($word,$data)=each (%thesaurus_db)) {
 2444:         my ($count,undef) = split /:/,$data;
 2445:         $Keywords{$word}++ if ($count > $avecount);
 2446:     }
 2447:     untie %thesaurus_db;
 2448:     # Remove special values from %Keywords.
 2449:     foreach my $value ('total.count','average.count') {
 2450:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2451:   }
 2452:     return 1;
 2453: }
 2454: 
 2455: ###################################################
 2456: 
 2457: =pod
 2458: 
 2459: =item * &keyword($word)
 2460: 
 2461: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2462: than the average number of times in the thesaurus database.  Calls 
 2463: &initialize_keywords
 2464: 
 2465: =cut
 2466: 
 2467: ###################################################
 2468: 
 2469: sub keyword {
 2470:     return if (!&initialize_keywords());
 2471:     my $word=lc(shift());
 2472:     $word=~s/\W//g;
 2473:     return exists($Keywords{$word});
 2474: }
 2475: 
 2476: ###############################################################
 2477: 
 2478: =pod 
 2479: 
 2480: =item * &get_related_words()
 2481: 
 2482: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2483: an array of words.  If the keyword is not in the thesaurus, an empty array
 2484: will be returned.  The order of the words returned is determined by the
 2485: database which holds them.
 2486: 
 2487: Uses global $thesaurus_db_file.
 2488: 
 2489: =cut
 2490: 
 2491: ###############################################################
 2492: sub get_related_words {
 2493:     my $keyword = shift;
 2494:     my %thesaurus_db;
 2495:     if (! -e $thesaurus_db_file) {
 2496:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2497:                                  "failed because the file does not exist");
 2498:         return ();
 2499:     }
 2500:     if (! tie(%thesaurus_db,'GDBM_File',
 2501:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2502:         return ();
 2503:     } 
 2504:     my @Words=();
 2505:     my $count=0;
 2506:     if (exists($thesaurus_db{$keyword})) {
 2507: 	# The first element is the number of times
 2508: 	# the word appears.  We do not need it now.
 2509: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2510: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2511: 	my $threshold=$mostfrequentcount/10;
 2512:         foreach my $possibleword (@RelatedWords) {
 2513:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2514:             if ($wordcount>$threshold) {
 2515: 		push(@Words,$word);
 2516:                 $count++;
 2517:                 if ($count>10) { last; }
 2518: 	    }
 2519:         }
 2520:     }
 2521:     untie %thesaurus_db;
 2522:     return @Words;
 2523: }
 2524: 
 2525: =pod
 2526: 
 2527: =back
 2528: 
 2529: =cut
 2530: 
 2531: # -------------------------------------------------------------- Plaintext name
 2532: =pod
 2533: 
 2534: =head1 User Name Functions
 2535: 
 2536: =over 4
 2537: 
 2538: =item * &plainname($uname,$udom,$first)
 2539: 
 2540: Takes a users logon name and returns it as a string in
 2541: "first middle last generation" form 
 2542: if $first is set to 'lastname' then it returns it as
 2543: 'lastname generation, firstname middlename' if their is a lastname
 2544: 
 2545: =cut
 2546: 
 2547: 
 2548: ###############################################################
 2549: sub plainname {
 2550:     my ($uname,$udom,$first)=@_;
 2551:     return if (!defined($uname) || !defined($udom));
 2552:     my %names=&getnames($uname,$udom);
 2553:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2554: 					  $names{'middlename'},
 2555: 					  $names{'lastname'},
 2556: 					  $names{'generation'},$first);
 2557:     $name=~s/^\s+//;
 2558:     $name=~s/\s+$//;
 2559:     $name=~s/\s+/ /g;
 2560:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2561:     return $name;
 2562: }
 2563: 
 2564: # -------------------------------------------------------------------- Nickname
 2565: =pod
 2566: 
 2567: =item * &nickname($uname,$udom)
 2568: 
 2569: Gets a users name and returns it as a string as
 2570: 
 2571: "&quot;nickname&quot;"
 2572: 
 2573: if the user has a nickname or
 2574: 
 2575: "first middle last generation"
 2576: 
 2577: if the user does not
 2578: 
 2579: =cut
 2580: 
 2581: sub nickname {
 2582:     my ($uname,$udom)=@_;
 2583:     return if (!defined($uname) || !defined($udom));
 2584:     my %names=&getnames($uname,$udom);
 2585:     my $name=$names{'nickname'};
 2586:     if ($name) {
 2587:        $name='&quot;'.$name.'&quot;'; 
 2588:     } else {
 2589:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2590: 	     $names{'lastname'}.' '.$names{'generation'};
 2591:        $name=~s/\s+$//;
 2592:        $name=~s/\s+/ /g;
 2593:     }
 2594:     return $name;
 2595: }
 2596: 
 2597: sub getnames {
 2598:     my ($uname,$udom)=@_;
 2599:     return if (!defined($uname) || !defined($udom));
 2600:     if ($udom eq 'public' && $uname eq 'public') {
 2601: 	return ('lastname' => &mt('Public'));
 2602:     }
 2603:     my $id=$uname.':'.$udom;
 2604:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2605:     if ($cached) {
 2606: 	return %{$names};
 2607:     } else {
 2608: 	my %loadnames=&Apache::lonnet::get('environment',
 2609:                     ['firstname','middlename','lastname','generation','nickname'],
 2610: 					 $udom,$uname);
 2611: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2612: 	return %loadnames;
 2613:     }
 2614: }
 2615: 
 2616: # -------------------------------------------------------------------- getemails
 2617: 
 2618: =pod
 2619: 
 2620: =item * &getemails($uname,$udom)
 2621: 
 2622: Gets a user's email information and returns it as a hash with keys:
 2623: notification, critnotification, permanentemail
 2624: 
 2625: For notification and critnotification, values are comma-separated lists 
 2626: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2627:  
 2628: 
 2629: =cut
 2630: 
 2631: 
 2632: sub getemails {
 2633:     my ($uname,$udom)=@_;
 2634:     if ($udom eq 'public' && $uname eq 'public') {
 2635: 	return;
 2636:     }
 2637:     if (!$udom) { $udom=$env{'user.domain'}; }
 2638:     if (!$uname) { $uname=$env{'user.name'}; }
 2639:     my $id=$uname.':'.$udom;
 2640:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2641:     if ($cached) {
 2642: 	return %{$names};
 2643:     } else {
 2644: 	my %loadnames=&Apache::lonnet::get('environment',
 2645:                     			   ['notification','critnotification',
 2646: 					    'permanentemail'],
 2647: 					   $udom,$uname);
 2648: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2649: 	return %loadnames;
 2650:     }
 2651: }
 2652: 
 2653: sub flush_email_cache {
 2654:     my ($uname,$udom)=@_;
 2655:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2656:     if (!$uname) { $uname=$env{'user.name'};   }
 2657:     return if ($udom eq 'public' && $uname eq 'public');
 2658:     my $id=$uname.':'.$udom;
 2659:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2660: }
 2661: 
 2662: # ------------------------------------------------------------------ Screenname
 2663: 
 2664: =pod
 2665: 
 2666: =item * &screenname($uname,$udom)
 2667: 
 2668: Gets a users screenname and returns it as a string
 2669: 
 2670: =cut
 2671: 
 2672: sub screenname {
 2673:     my ($uname,$udom)=@_;
 2674:     if ($uname eq $env{'user.name'} &&
 2675: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2676:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2677:     return $names{'screenname'};
 2678: }
 2679: 
 2680: 
 2681: # ------------------------------------------------------------- Message Wrapper
 2682: 
 2683: sub messagewrapper {
 2684:     my ($link,$username,$domain,$subject,$text)=@_;
 2685:     return 
 2686:         '<a href="/adm/email?compose=individual&amp;'.
 2687:         'recname='.$username.'&amp;recdom='.$domain.
 2688: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2689:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2690: }
 2691: # --------------------------------------------------------------- Notes Wrapper
 2692: 
 2693: sub noteswrapper {
 2694:     my ($link,$un,$do)=@_;
 2695:     return 
 2696: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2697: }
 2698: # ------------------------------------------------------------- Aboutme Wrapper
 2699: 
 2700: sub aboutmewrapper {
 2701:     my ($link,$username,$domain,$target)=@_;
 2702:     if (!defined($username)  && !defined($domain)) {
 2703:         return;
 2704:     }
 2705:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2706: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2707: }
 2708: 
 2709: # ------------------------------------------------------------ Syllabus Wrapper
 2710: 
 2711: 
 2712: sub syllabuswrapper {
 2713:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2714:     if ($fontcolor) { 
 2715:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2716:     }
 2717:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2718: }
 2719: 
 2720: sub track_student_link {
 2721:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2722:     my $link ="/adm/trackstudent?";
 2723:     my $title = 'View recent activity';
 2724:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2725:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2726:         $link .= "selected_student=$sname:$sdom";
 2727:         $title .= ' of this student';
 2728:     } 
 2729:     if (defined($target) && $target !~ /^\s*$/) {
 2730:         $target = qq{target="$target"};
 2731:     } else {
 2732:         $target = '';
 2733:     }
 2734:     if ($start) { $link.='&amp;start='.$start; }
 2735:     $title = &mt($title);
 2736:     $linktext = &mt($linktext);
 2737:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2738: 	&help_open_topic('View_recent_activity');
 2739: }
 2740: 
 2741: # ===================================================== Display a student photo
 2742: 
 2743: 
 2744: sub student_image_tag {
 2745:     my ($domain,$user)=@_;
 2746:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2747:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2748: 	return '<img src="'.$imgsrc.'" align="right" />';
 2749:     } else {
 2750: 	return '';
 2751:     }
 2752: }
 2753: 
 2754: =pod
 2755: 
 2756: =back
 2757: 
 2758: =head1 Access .tab File Data
 2759: 
 2760: =over 4
 2761: 
 2762: =item * &languageids() 
 2763: 
 2764: returns list of all language ids
 2765: 
 2766: =cut
 2767: 
 2768: sub languageids {
 2769:     return sort(keys(%language));
 2770: }
 2771: 
 2772: =pod
 2773: 
 2774: =item * &languagedescription() 
 2775: 
 2776: returns description of a specified language id
 2777: 
 2778: =cut
 2779: 
 2780: sub languagedescription {
 2781:     my $code=shift;
 2782:     return  ($supported_language{$code}?'* ':'').
 2783:             $language{$code}.
 2784: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2785: }
 2786: 
 2787: sub plainlanguagedescription {
 2788:     my $code=shift;
 2789:     return $language{$code};
 2790: }
 2791: 
 2792: sub supportedlanguagecode {
 2793:     my $code=shift;
 2794:     return $supported_language{$code};
 2795: }
 2796: 
 2797: =pod
 2798: 
 2799: =item * &copyrightids() 
 2800: 
 2801: returns list of all copyrights
 2802: 
 2803: =cut
 2804: 
 2805: sub copyrightids {
 2806:     return sort(keys(%cprtag));
 2807: }
 2808: 
 2809: =pod
 2810: 
 2811: =item * &copyrightdescription() 
 2812: 
 2813: returns description of a specified copyright id
 2814: 
 2815: =cut
 2816: 
 2817: sub copyrightdescription {
 2818:     return &mt($cprtag{shift(@_)});
 2819: }
 2820: 
 2821: =pod
 2822: 
 2823: =item * &source_copyrightids() 
 2824: 
 2825: returns list of all source copyrights
 2826: 
 2827: =cut
 2828: 
 2829: sub source_copyrightids {
 2830:     return sort(keys(%scprtag));
 2831: }
 2832: 
 2833: =pod
 2834: 
 2835: =item * &source_copyrightdescription() 
 2836: 
 2837: returns description of a specified source copyright id
 2838: 
 2839: =cut
 2840: 
 2841: sub source_copyrightdescription {
 2842:     return &mt($scprtag{shift(@_)});
 2843: }
 2844: 
 2845: =pod
 2846: 
 2847: =item * &filecategories() 
 2848: 
 2849: returns list of all file categories
 2850: 
 2851: =cut
 2852: 
 2853: sub filecategories {
 2854:     return sort(keys(%category_extensions));
 2855: }
 2856: 
 2857: =pod
 2858: 
 2859: =item * &filecategorytypes() 
 2860: 
 2861: returns list of file types belonging to a given file
 2862: category
 2863: 
 2864: =cut
 2865: 
 2866: sub filecategorytypes {
 2867:     my ($cat) = @_;
 2868:     return @{$category_extensions{lc($cat)}};
 2869: }
 2870: 
 2871: =pod
 2872: 
 2873: =item * &fileembstyle() 
 2874: 
 2875: returns embedding style for a specified file type
 2876: 
 2877: =cut
 2878: 
 2879: sub fileembstyle {
 2880:     return $fe{lc(shift(@_))};
 2881: }
 2882: 
 2883: sub filemimetype {
 2884:     return $fm{lc(shift(@_))};
 2885: }
 2886: 
 2887: 
 2888: sub filecategoryselect {
 2889:     my ($name,$value)=@_;
 2890:     return &select_form($value,$name,
 2891: 			'' => &mt('Any category'),
 2892: 			map { $_,$_ } sort(keys(%category_extensions)));
 2893: }
 2894: 
 2895: =pod
 2896: 
 2897: =item * &filedescription() 
 2898: 
 2899: returns description for a specified file type
 2900: 
 2901: =cut
 2902: 
 2903: sub filedescription {
 2904:     my $file_description = $fd{lc(shift())};
 2905:     $file_description =~ s:([\[\]]):~$1:g;
 2906:     return &mt($file_description);
 2907: }
 2908: 
 2909: =pod
 2910: 
 2911: =item * &filedescriptionex() 
 2912: 
 2913: returns description for a specified file type with
 2914: extra formatting
 2915: 
 2916: =cut
 2917: 
 2918: sub filedescriptionex {
 2919:     my $ex=shift;
 2920:     my $file_description = $fd{lc($ex)};
 2921:     $file_description =~ s:([\[\]]):~$1:g;
 2922:     return '.'.$ex.' '.&mt($file_description);
 2923: }
 2924: 
 2925: # End of .tab access
 2926: =pod
 2927: 
 2928: =back
 2929: 
 2930: =cut
 2931: 
 2932: # ------------------------------------------------------------------ File Types
 2933: sub fileextensions {
 2934:     return sort(keys(%fe));
 2935: }
 2936: 
 2937: # ----------------------------------------------------------- Display Languages
 2938: # returns a hash with all desired display languages
 2939: #
 2940: 
 2941: sub display_languages {
 2942:     my %languages=();
 2943:     foreach my $lang (&preferred_languages()) {
 2944: 	$languages{$lang}=1;
 2945:     }
 2946:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2947:     if ($env{'form.displaylanguage'}) {
 2948: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2949: 	    $languages{$lang}=1;
 2950:         }
 2951:     }
 2952:     return %languages;
 2953: }
 2954: 
 2955: sub preferred_languages {
 2956:     my @languages=();
 2957:     if (($env{'request.role.adv'}) && ($env{'form.languages'})) {
 2958:         @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$env{'form.languages'}));
 2959:     }
 2960:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2961: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2962: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2963:     }
 2964: 
 2965:     if ($env{'environment.languages'}) {
 2966: 	@languages=(@languages,
 2967: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
 2968:     }
 2969:     my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
 2970:     if ($browser) {
 2971: 	my @browser = 
 2972: 	    map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
 2973: 	push(@languages,@browser);
 2974:     }
 2975: 
 2976:     foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
 2977:                          $Apache::lonnet::perlvar{'lonDefDomain'}) {
 2978:         if ($domtype ne '') {
 2979:             my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
 2980:             if ($domdefs{'lang_def'} ne '') {
 2981:                 push(@languages,$domdefs{'lang_def'});
 2982:             }
 2983:         }
 2984:     }
 2985: # turn "en-ca" into "en-ca,en"
 2986:     my @genlanguages;
 2987:     foreach my $lang (@languages) {
 2988: 	unless ($lang=~/\w/) { next; }
 2989: 	push(@genlanguages,$lang);
 2990: 	if ($lang=~/(\-|\_)/) {
 2991: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2992: 	}
 2993:     }
 2994:     #uniqueify the languages list
 2995:     my %count;
 2996:     @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
 2997:     return @genlanguages;
 2998: }
 2999: 
 3000: sub languages {
 3001:     my ($possible_langs) = @_;
 3002:     my @preferred_langs = &preferred_languages();
 3003:     if (!ref($possible_langs)) {
 3004: 	if( wantarray ) {
 3005: 	    return @preferred_langs;
 3006: 	} else {
 3007: 	    return $preferred_langs[0];
 3008: 	}
 3009:     }
 3010:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3011:     my @preferred_possibilities;
 3012:     foreach my $preferred_lang (@preferred_langs) {
 3013: 	if (exists($possibilities{$preferred_lang})) {
 3014: 	    push(@preferred_possibilities, $preferred_lang);
 3015: 	}
 3016:     }
 3017:     if( wantarray ) {
 3018: 	return @preferred_possibilities;
 3019:     }
 3020:     return $preferred_possibilities[0];
 3021: }
 3022: 
 3023: ###############################################################
 3024: ##               Student Answer Attempts                     ##
 3025: ###############################################################
 3026: 
 3027: =pod
 3028: 
 3029: =head1 Alternate Problem Views
 3030: 
 3031: =over 4
 3032: 
 3033: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3034:     $getattempt, $regexp, $gradesub)
 3035: 
 3036: Return string with previous attempt on problem. Arguments:
 3037: 
 3038: =over 4
 3039: 
 3040: =item * $symb: Problem, including path
 3041: 
 3042: =item * $username: username of the desired student
 3043: 
 3044: =item * $domain: domain of the desired student
 3045: 
 3046: =item * $course: Course ID
 3047: 
 3048: =item * $getattempt: Leave blank for all attempts, otherwise put
 3049:     something
 3050: 
 3051: =item * $regexp: if string matches this regexp, the string will be
 3052:     sent to $gradesub
 3053: 
 3054: =item * $gradesub: routine that processes the string if it matches $regexp
 3055: 
 3056: =back
 3057: 
 3058: The output string is a table containing all desired attempts, if any.
 3059: 
 3060: =cut
 3061: 
 3062: sub get_previous_attempt {
 3063:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3064:   my $prevattempts='';
 3065:   no strict 'refs';
 3066:   if ($symb) {
 3067:     my (%returnhash)=
 3068:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3069:     if ($returnhash{'version'}) {
 3070:       my %lasthash=();
 3071:       my $version;
 3072:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3073:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3074: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3075:         }
 3076:       }
 3077:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3078:       $prevattempts.='<th>'.&mt('History').'</th>';
 3079:       foreach my $key (sort(keys(%lasthash))) {
 3080: 	my ($ign,@parts) = split(/\./,$key);
 3081: 	if ($#parts > 0) {
 3082: 	  my $data=$parts[-1];
 3083: 	  pop(@parts);
 3084: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3085: 	} else {
 3086: 	  if ($#parts == 0) {
 3087: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3088: 	  } else {
 3089: 	    $prevattempts.='<th>'.$ign.'</th>';
 3090: 	  }
 3091: 	}
 3092:       }
 3093:       $prevattempts.=&end_data_table_header_row();
 3094:       if ($getattempt eq '') {
 3095: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3096: 	  $prevattempts.=&start_data_table_row().
 3097: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3098: 	    foreach my $key (sort(keys(%lasthash))) {
 3099: 		my $value = &format_previous_attempt_value($key,
 3100: 							   $returnhash{$version.':'.$key});
 3101: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3102: 	    }
 3103: 	  $prevattempts.=&end_data_table_row();
 3104: 	 }
 3105:       }
 3106:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3107:       foreach my $key (sort(keys(%lasthash))) {
 3108: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3109: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3110: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3111:       }
 3112:       $prevattempts.= &end_data_table_row().&end_data_table();
 3113:     } else {
 3114:       $prevattempts=
 3115: 	  &start_data_table().&start_data_table_row().
 3116: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3117: 	  &end_data_table_row().&end_data_table();
 3118:     }
 3119:   } else {
 3120:     $prevattempts=
 3121: 	  &start_data_table().&start_data_table_row().
 3122: 	  '<td>'.&mt('No data.').'</td>'.
 3123: 	  &end_data_table_row().&end_data_table();
 3124:   }
 3125: }
 3126: 
 3127: sub format_previous_attempt_value {
 3128:     my ($key,$value) = @_;
 3129:     if ($key =~ /timestamp/) {
 3130: 	$value = &Apache::lonlocal::locallocaltime($value);
 3131:     } elsif (ref($value) eq 'ARRAY') {
 3132: 	$value = '('.join(', ', @{ $value }).')';
 3133:     } else {
 3134: 	$value = &unescape($value);
 3135:     }
 3136:     return $value;
 3137: }
 3138: 
 3139: 
 3140: sub relative_to_absolute {
 3141:     my ($url,$output)=@_;
 3142:     my $parser=HTML::TokeParser->new(\$output);
 3143:     my $token;
 3144:     my $thisdir=$url;
 3145:     my @rlinks=();
 3146:     while ($token=$parser->get_token) {
 3147: 	if ($token->[0] eq 'S') {
 3148: 	    if ($token->[1] eq 'a') {
 3149: 		if ($token->[2]->{'href'}) {
 3150: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3151: 		}
 3152: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3153: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3154: 	    } elsif ($token->[1] eq 'base') {
 3155: 		$thisdir=$token->[2]->{'href'};
 3156: 	    }
 3157: 	}
 3158:     }
 3159:     $thisdir=~s-/[^/]*$--;
 3160:     foreach my $link (@rlinks) {
 3161: 	unless (($link=~/^http:\/\//i) ||
 3162: 		($link=~/^\//) ||
 3163: 		($link=~/^javascript:/i) ||
 3164: 		($link=~/^mailto:/i) ||
 3165: 		($link=~/^\#/)) {
 3166: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3167: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3168: 	}
 3169:     }
 3170: # -------------------------------------------------- Deal with Applet codebases
 3171:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3172:     return $output;
 3173: }
 3174: 
 3175: =pod
 3176: 
 3177: =item * &get_student_view()
 3178: 
 3179: show a snapshot of what student was looking at
 3180: 
 3181: =cut
 3182: 
 3183: sub get_student_view {
 3184:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3185:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3186:   my (%form);
 3187:   my @elements=('symb','courseid','domain','username');
 3188:   foreach my $element (@elements) {
 3189:       $form{'grade_'.$element}=eval '$'.$element #'
 3190:   }
 3191:   if (defined($moreenv)) {
 3192:       %form=(%form,%{$moreenv});
 3193:   }
 3194:   if (defined($target)) { $form{'grade_target'} = $target; }
 3195:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3196:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3197:   $userview=~s/\<body[^\>]*\>//gi;
 3198:   $userview=~s/\<\/body\>//gi;
 3199:   $userview=~s/\<html\>//gi;
 3200:   $userview=~s/\<\/html\>//gi;
 3201:   $userview=~s/\<head\>//gi;
 3202:   $userview=~s/\<\/head\>//gi;
 3203:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3204:   $userview=&relative_to_absolute($feedurl,$userview);
 3205:   if (wantarray) {
 3206:      return ($userview,$response);
 3207:   } else {
 3208:      return $userview;
 3209:   }
 3210: }
 3211: 
 3212: sub get_student_view_with_retries {
 3213:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3214: 
 3215:     my $ok = 0;                 # True if we got a good response.
 3216:     my $content;
 3217:     my $response;
 3218: 
 3219:     # Try to get the student_view done. within the retries count:
 3220:     
 3221:     do {
 3222:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3223:          $ok      = $response->is_success;
 3224:          if (!$ok) {
 3225:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3226:          }
 3227:          $retries--;
 3228:     } while (!$ok && ($retries > 0));
 3229:     
 3230:     if (!$ok) {
 3231:        $content = '';          # On error return an empty content.
 3232:     }
 3233:     if (wantarray) {
 3234:        return ($content, $response);
 3235:     } else {
 3236:        return $content;
 3237:     }
 3238: }
 3239: 
 3240: =pod
 3241: 
 3242: =item * &get_student_answers() 
 3243: 
 3244: show a snapshot of how student was answering problem
 3245: 
 3246: =cut
 3247: 
 3248: sub get_student_answers {
 3249:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3250:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3251:   my (%moreenv);
 3252:   my @elements=('symb','courseid','domain','username');
 3253:   foreach my $element (@elements) {
 3254:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3255:   }
 3256:   $moreenv{'grade_target'}='answer';
 3257:   %moreenv=(%form,%moreenv);
 3258:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3259:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3260:   return $userview;
 3261: }
 3262: 
 3263: =pod
 3264: 
 3265: =item * &submlink()
 3266: 
 3267: Inputs: $text $uname $udom $symb $target
 3268: 
 3269: Returns: A link to grades.pm such as to see the SUBM view of a student
 3270: 
 3271: =cut
 3272: 
 3273: ###############################################
 3274: sub submlink {
 3275:     my ($text,$uname,$udom,$symb,$target)=@_;
 3276:     if (!($uname && $udom)) {
 3277: 	(my $cursymb, my $courseid,$udom,$uname)=
 3278: 	    &Apache::lonnet::whichuser($symb);
 3279: 	if (!$symb) { $symb=$cursymb; }
 3280:     }
 3281:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3282:     $symb=&escape($symb);
 3283:     if ($target) { $target="target=\"$target\""; }
 3284:     return '<a href="/adm/grades?&command=submission&'.
 3285: 	'symb='.$symb.'&student='.$uname.
 3286: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3287: }
 3288: ##############################################
 3289: 
 3290: =pod
 3291: 
 3292: =item * &pgrdlink()
 3293: 
 3294: Inputs: $text $uname $udom $symb $target
 3295: 
 3296: Returns: A link to grades.pm such as to see the PGRD view of a student
 3297: 
 3298: =cut
 3299: 
 3300: ###############################################
 3301: sub pgrdlink {
 3302:     my $link=&submlink(@_);
 3303:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3304:     return $link;
 3305: }
 3306: ##############################################
 3307: 
 3308: =pod
 3309: 
 3310: =item * &pprmlink()
 3311: 
 3312: Inputs: $text $uname $udom $symb $target
 3313: 
 3314: Returns: A link to parmset.pm such as to see the PPRM view of a
 3315: student and a specific resource
 3316: 
 3317: =cut
 3318: 
 3319: ###############################################
 3320: sub pprmlink {
 3321:     my ($text,$uname,$udom,$symb,$target)=@_;
 3322:     if (!($uname && $udom)) {
 3323: 	(my $cursymb, my $courseid,$udom,$uname)=
 3324: 	    &Apache::lonnet::whichuser($symb);
 3325: 	if (!$symb) { $symb=$cursymb; }
 3326:     }
 3327:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3328:     $symb=&escape($symb);
 3329:     if ($target) { $target="target=\"$target\""; }
 3330:     return '<a href="/adm/parmset?command=set&amp;'.
 3331: 	'symb='.$symb.'&amp;uname='.$uname.
 3332: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3333: }
 3334: ##############################################
 3335: 
 3336: =pod
 3337: 
 3338: =back
 3339: 
 3340: =cut
 3341: 
 3342: ###############################################
 3343: 
 3344: 
 3345: sub timehash {
 3346:     my @ltime=localtime(shift);
 3347:     return ( 'seconds' => $ltime[0],
 3348:              'minutes' => $ltime[1],
 3349:              'hours'   => $ltime[2],
 3350:              'day'     => $ltime[3],
 3351:              'month'   => $ltime[4]+1,
 3352:              'year'    => $ltime[5]+1900,
 3353:              'weekday' => $ltime[6],
 3354:              'dayyear' => $ltime[7]+1,
 3355:              'dlsav'   => $ltime[8] );
 3356: }
 3357: 
 3358: sub utc_string {
 3359:     my ($date)=@_;
 3360:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3361: }
 3362: 
 3363: sub maketime {
 3364:     my %th=@_;
 3365:     return POSIX::mktime(
 3366:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3367:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3368: }
 3369: 
 3370: #########################################
 3371: 
 3372: sub findallcourses {
 3373:     my ($roles,$uname,$udom) = @_;
 3374:     my %roles;
 3375:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3376:     my %courses;
 3377:     my $now=time;
 3378:     if (!defined($uname)) {
 3379:         $uname = $env{'user.name'};
 3380:     }
 3381:     if (!defined($udom)) {
 3382:         $udom = $env{'user.domain'};
 3383:     }
 3384:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3385:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3386:         if (!%roles) {
 3387:             %roles = (
 3388:                        cc => 1,
 3389:                        in => 1,
 3390:                        ep => 1,
 3391:                        ta => 1,
 3392:                        cr => 1,
 3393:                        st => 1,
 3394:              );
 3395:         }
 3396:         foreach my $entry (keys(%roleshash)) {
 3397:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3398:             if ($trole =~ /^cr/) { 
 3399:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3400:             } else {
 3401:                 next if (!exists($roles{$trole}));
 3402:             }
 3403:             if ($tend) {
 3404:                 next if ($tend < $now);
 3405:             }
 3406:             if ($tstart) {
 3407:                 next if ($tstart > $now);
 3408:             }
 3409:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3410:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3411:             if ($secpart eq '') {
 3412:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3413:                 $sec = 'none';
 3414:                 $realsec = '';
 3415:             } else {
 3416:                 $cnum = $cnumpart;
 3417:                 ($sec,$role) = split(/_/,$secpart);
 3418:                 $realsec = $sec;
 3419:             }
 3420:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3421:         }
 3422:     } else {
 3423:         foreach my $key (keys(%env)) {
 3424: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3425:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3426: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3427: 	        next if ($role eq 'ca' || $role eq 'aa');
 3428: 	        next if (%roles && !exists($roles{$role}));
 3429: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3430:                 my $active=1;
 3431:                 if ($starttime) {
 3432: 		    if ($now<$starttime) { $active=0; }
 3433:                 }
 3434:                 if ($endtime) {
 3435:                     if ($now>$endtime) { $active=0; }
 3436:                 }
 3437:                 if ($active) {
 3438:                     if ($sec eq '') {
 3439:                         $sec = 'none';
 3440:                     }
 3441:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3442:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3443:                 }
 3444:             }
 3445:         }
 3446:     }
 3447:     return %courses;
 3448: }
 3449: 
 3450: ###############################################
 3451: 
 3452: sub blockcheck {
 3453:     my ($setters,$activity,$uname,$udom) = @_;
 3454: 
 3455:     if (!defined($udom)) {
 3456:         $udom = $env{'user.domain'};
 3457:     }
 3458:     if (!defined($uname)) {
 3459:         $uname = $env{'user.name'};
 3460:     }
 3461: 
 3462:     # If uname and udom are for a course, check for blocks in the course.
 3463: 
 3464:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3465:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3466:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3467:         return ($startblock,$endblock);
 3468:     }
 3469: 
 3470:     my $startblock = 0;
 3471:     my $endblock = 0;
 3472:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3473: 
 3474:     # If uname is for a user, and activity is course-specific, i.e.,
 3475:     # boards, chat or groups, check for blocking in current course only.
 3476: 
 3477:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3478:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3479:         foreach my $key (keys(%live_courses)) {
 3480:             if ($key ne $env{'request.course.id'}) {
 3481:                 delete($live_courses{$key});
 3482:             }
 3483:         }
 3484:     }
 3485: 
 3486:     my $otheruser = 0;
 3487:     my %own_courses;
 3488:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3489:         # Resource belongs to user other than current user.
 3490:         $otheruser = 1;
 3491:         # Gather courses for current user
 3492:         %own_courses = 
 3493:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3494:     }
 3495: 
 3496:     # Gather active course roles - course coordinator, instructor, 
 3497:     # exam proctor, ta, student, or custom role.
 3498: 
 3499:     foreach my $course (keys(%live_courses)) {
 3500:         my ($cdom,$cnum);
 3501:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3502:             $cdom = $env{'course.'.$course.'.domain'};
 3503:             $cnum = $env{'course.'.$course.'.num'};
 3504:         } else {
 3505:             ($cdom,$cnum) = split(/_/,$course); 
 3506:         }
 3507:         my $no_ownblock = 0;
 3508:         my $no_userblock = 0;
 3509:         if ($otheruser && $activity ne 'com') {
 3510:             # Check if current user has 'evb' priv for this
 3511:             if (defined($own_courses{$course})) {
 3512:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3513:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3514:                     if ($sec ne 'none') {
 3515:                         $checkrole .= '/'.$sec;
 3516:                     }
 3517:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3518:                         $no_ownblock = 1;
 3519:                         last;
 3520:                     }
 3521:                 }
 3522:             }
 3523:             # if they have 'evb' priv and are currently not playing student
 3524:             next if (($no_ownblock) &&
 3525:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3526:         }
 3527:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3528:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3529:             if ($sec ne 'none') {
 3530:                 $checkrole .= '/'.$sec;
 3531:             }
 3532:             if ($otheruser) {
 3533:                 # Resource belongs to user other than current user.
 3534:                 # Assemble privs for that user, and check for 'evb' priv.
 3535:                 my ($trole,$tdom,$tnum,$tsec);
 3536:                 my $entry = $live_courses{$course}{$sec};
 3537:                 if ($entry =~ /^cr/) {
 3538:                     ($trole,$tdom,$tnum,$tsec) = 
 3539:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3540:                 } else {
 3541:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3542:                 }
 3543:                 my ($spec,$area,$trest,%allroles,%userroles);
 3544:                 $area = '/'.$tdom.'/'.$tnum;
 3545:                 $trest = $tnum;
 3546:                 if ($tsec ne '') {
 3547:                     $area .= '/'.$tsec;
 3548:                     $trest .= '/'.$tsec;
 3549:                 }
 3550:                 $spec = $trole.'.'.$area;
 3551:                 if ($trole =~ /^cr/) {
 3552:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3553:                                                       $tdom,$spec,$trest,$area);
 3554:                 } else {
 3555:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3556:                                                        $tdom,$spec,$trest,$area);
 3557:                 }
 3558:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3559:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3560:                     if ($1) {
 3561:                         $no_userblock = 1;
 3562:                         last;
 3563:                     }
 3564:                 }
 3565:             } else {
 3566:                 # Resource belongs to current user
 3567:                 # Check for 'evb' priv via lonnet::allowed().
 3568:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3569:                     $no_ownblock = 1;
 3570:                     last;
 3571:                 }
 3572:             }
 3573:         }
 3574:         # if they have the evb priv and are currently not playing student
 3575:         next if (($no_ownblock) &&
 3576:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3577:         next if ($no_userblock);
 3578: 
 3579:         # Retrieve blocking times and identity of blocker for course
 3580:         # of specified user, unless user has 'evb' privilege.
 3581:         
 3582:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3583:         if (($start != 0) && 
 3584:             (($startblock == 0) || ($startblock > $start))) {
 3585:             $startblock = $start;
 3586:         }
 3587:         if (($end != 0)  &&
 3588:             (($endblock == 0) || ($endblock < $end))) {
 3589:             $endblock = $end;
 3590:         }
 3591:     }
 3592:     return ($startblock,$endblock);
 3593: }
 3594: 
 3595: sub get_blocks {
 3596:     my ($setters,$activity,$cdom,$cnum) = @_;
 3597:     my $startblock = 0;
 3598:     my $endblock = 0;
 3599:     my $course = $cdom.'_'.$cnum;
 3600:     $setters->{$course} = {};
 3601:     $setters->{$course}{'staff'} = [];
 3602:     $setters->{$course}{'times'} = [];
 3603:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3604:     foreach my $record (keys(%records)) {
 3605:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3606:         if ($start <= time && $end >= time) {
 3607:             my ($staff_name,$staff_dom,$title,$blocks) =
 3608:                 &parse_block_record($records{$record});
 3609:             if ($blocks->{$activity} eq 'on') {
 3610:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3611:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3612:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3613:                     $startblock = $start;
 3614:                 }
 3615:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3616:                     $endblock = $end;
 3617:                 }
 3618:             }
 3619:         }
 3620:     }
 3621:     return ($startblock,$endblock);
 3622: }
 3623: 
 3624: sub parse_block_record {
 3625:     my ($record) = @_;
 3626:     my ($setuname,$setudom,$title,$blocks);
 3627:     if (ref($record) eq 'HASH') {
 3628:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3629:         $title = &unescape($record->{'event'});
 3630:         $blocks = $record->{'blocks'};
 3631:     } else {
 3632:         my @data = split(/:/,$record,3);
 3633:         if (scalar(@data) eq 2) {
 3634:             $title = $data[1];
 3635:             ($setuname,$setudom) = split(/@/,$data[0]);
 3636:         } else {
 3637:             ($setuname,$setudom,$title) = @data;
 3638:         }
 3639:         $blocks = { 'com' => 'on' };
 3640:     }
 3641:     return ($setuname,$setudom,$title,$blocks);
 3642: }
 3643: 
 3644: sub build_block_table {
 3645:     my ($startblock,$endblock,$setters) = @_;
 3646:     my %lt = &Apache::lonlocal::texthash(
 3647:         'cacb' => 'Currently active communication blocks',
 3648:         'cour' => 'Course',
 3649:         'dura' => 'Duration',
 3650:         'blse' => 'Block set by'
 3651:     );
 3652:     my $output;
 3653:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3654:     $output .= &start_data_table();
 3655:     $output .= '
 3656: <tr>
 3657:  <th>'.$lt{'cour'}.'</th>
 3658:  <th>'.$lt{'dura'}.'</th>
 3659:  <th>'.$lt{'blse'}.'</th>
 3660: </tr>
 3661: ';
 3662:     foreach my $course (keys(%{$setters})) {
 3663:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3664:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3665:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3666:             my $fullname = &plainname($uname,$udom);
 3667:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3668:                 && $env{'user.name'} ne 'public' 
 3669:                 && $env{'user.domain'} ne 'public') {
 3670:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3671:             }
 3672:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3673:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3674:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3675:             $output .= &Apache::loncommon::start_data_table_row().
 3676:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3677:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3678:                        '<td>'.$fullname.'</td>'.
 3679:                         &Apache::loncommon::end_data_table_row();
 3680:         }
 3681:     }
 3682:     $output .= &end_data_table();
 3683: }
 3684: 
 3685: sub blocking_status {
 3686:     my ($activity,$uname,$udom) = @_;
 3687:     my %setters;
 3688:     my ($blocked,$output,$ownitem,$is_course);
 3689:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3690:     if ($startblock && $endblock) {
 3691:         $blocked = 1;
 3692:         if (wantarray) {
 3693:             my $category;
 3694:             if ($activity eq 'boards') {
 3695:                 $category = 'Discussion posts in this course';
 3696:             } elsif ($activity eq 'blogs') {
 3697:                 $category = 'Blogs';
 3698:             } elsif ($activity eq 'port') {
 3699:                 if (defined($uname) && defined($udom)) {
 3700:                     if ($uname eq $env{'user.name'} &&
 3701:                         $udom eq $env{'user.domain'}) {
 3702:                         $ownitem = 1;
 3703:                     }
 3704:                 }
 3705:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3706:                 if ($ownitem) { 
 3707:                     $category = 'Your portfolio files';  
 3708:                 } elsif ($is_course) {
 3709:                     my $coursedesc;
 3710:                     foreach my $course (keys(%setters)) {
 3711:                         my %courseinfo =
 3712:                              &Apache::lonnet::coursedescription($course);
 3713:                         $coursedesc = $courseinfo{'description'};
 3714:                     }
 3715:                     $category = "Group files in the course '$coursedesc'";
 3716:                 } else {
 3717:                     $category = 'Portfolio files belonging to ';
 3718:                     if ($env{'user.name'} eq 'public' && 
 3719:                         $env{'user.domain'} eq 'public') {
 3720:                         $category .= &plainname($uname,$udom);
 3721:                     } else {
 3722:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3723:                     }
 3724:                 }
 3725:             } elsif ($activity eq 'groups') {
 3726:                 $category = 'Groups in this course';
 3727:             }
 3728:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3729:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3730:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3731:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3732:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3733:             }
 3734:         }
 3735:     }
 3736:     if (wantarray) {
 3737:         return ($blocked,$output);
 3738:     } else {
 3739:         return $blocked;
 3740:     }
 3741: }
 3742: 
 3743: ###############################################
 3744: 
 3745: =pod
 3746: 
 3747: =head1 Domain Template Functions
 3748: 
 3749: =over 4
 3750: 
 3751: =item * &determinedomain()
 3752: 
 3753: Inputs: $domain (usually will be undef)
 3754: 
 3755: Returns: Determines which domain should be used for designs
 3756: 
 3757: =cut
 3758: 
 3759: ###############################################
 3760: sub determinedomain {
 3761:     my $domain=shift;
 3762:     if (! $domain) {
 3763:         # Determine domain if we have not been given one
 3764:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3765:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3766:         if ($env{'request.role.domain'}) { 
 3767:             $domain=$env{'request.role.domain'}; 
 3768:         }
 3769:     }
 3770:     return $domain;
 3771: }
 3772: ###############################################
 3773: 
 3774: sub devalidate_domconfig_cache {
 3775:     my ($udom)=@_;
 3776:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3777: }
 3778: 
 3779: # ---------------------- Get domain configuration for a domain
 3780: sub get_domainconf {
 3781:     my ($udom) = @_;
 3782:     my $cachetime=1800;
 3783:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3784:     if (defined($cached)) { return %{$result}; }
 3785: 
 3786:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3787: 					     ['login','rolecolors'],$udom);
 3788:     my (%designhash,%legacy);
 3789:     if (keys(%domconfig) > 0) {
 3790:         if (ref($domconfig{'login'}) eq 'HASH') {
 3791:             if (keys(%{$domconfig{'login'}})) {
 3792:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3793:                     $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3794:                 }
 3795:             } else {
 3796:                 $legacy{'login'} = 1;
 3797:             }
 3798:         } else {
 3799:             $legacy{'login'} = 1;
 3800:         }
 3801:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3802:             if (keys(%{$domconfig{'rolecolors'}})) {
 3803:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3804:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3805:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3806:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3807:                         }
 3808:                     }
 3809:                 }
 3810:             } else {
 3811:                 $legacy{'rolecolors'} = 1;
 3812:             }
 3813:         } else {
 3814:             $legacy{'rolecolors'} = 1;
 3815:         }
 3816:         if (keys(%legacy) > 0) {
 3817:             my %legacyhash = &get_legacy_domconf($udom);
 3818:             foreach my $item (keys(%legacyhash)) {
 3819:                 if ($item =~ /^\Q$udom\E\.login/) {
 3820:                     if ($legacy{'login'}) { 
 3821:                         $designhash{$item} = $legacyhash{$item};
 3822:                     }
 3823:                 } else {
 3824:                     if ($legacy{'rolecolors'}) {
 3825:                         $designhash{$item} = $legacyhash{$item};
 3826:                     }
 3827:                 }
 3828:             }
 3829:         }
 3830:     } else {
 3831:         %designhash = &get_legacy_domconf($udom); 
 3832:     }
 3833:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 3834: 				  $cachetime);
 3835:     return %designhash;
 3836: }
 3837: 
 3838: sub get_legacy_domconf {
 3839:     my ($udom) = @_;
 3840:     my %legacyhash;
 3841:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 3842:     my $designfile =  $designdir.'/'.$udom.'.tab';
 3843:     if (-e $designfile) {
 3844:         if ( open (my $fh,"<$designfile") ) {
 3845:             while (my $line = <$fh>) {
 3846:                 next if ($line =~ /^\#/);
 3847:                 chomp($line);
 3848:                 my ($key,$val)=(split(/\=/,$line));
 3849:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 3850:             }
 3851:             close($fh);
 3852:         }
 3853:     }
 3854:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 3855:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 3856:     }
 3857:     return %legacyhash;
 3858: }
 3859: 
 3860: =pod
 3861: 
 3862: =item * &domainlogo()
 3863: 
 3864: Inputs: $domain (usually will be undef)
 3865: 
 3866: Returns: A link to a domain logo, if the domain logo exists.
 3867: If the domain logo does not exist, a description of the domain.
 3868: 
 3869: =cut
 3870: 
 3871: ###############################################
 3872: sub domainlogo {
 3873:     my $domain = &determinedomain(shift);
 3874:     my %designhash = &get_domainconf($domain);    
 3875:     # See if there is a logo
 3876:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 3877:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 3878:         if ($imgsrc =~ m{^/(adm|res)/}) {
 3879: 	    if ($imgsrc =~ m{^/res/}) {
 3880: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 3881: 		&Apache::lonnet::repcopy($local_name);
 3882: 	    }
 3883: 	   $imgsrc = &lonhttpdurl($imgsrc);
 3884:         } 
 3885:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 3886:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 3887:         return &Apache::lonnet::domain($domain,'description');
 3888:     } else {
 3889:         return '';
 3890:     }
 3891: }
 3892: ##############################################
 3893: 
 3894: =pod
 3895: 
 3896: =item * &designparm()
 3897: 
 3898: Inputs: $which parameter; $domain (usually will be undef)
 3899: 
 3900: Returns: value of designparamter $which
 3901: 
 3902: =cut
 3903: 
 3904: 
 3905: ##############################################
 3906: sub designparm {
 3907:     my ($which,$domain)=@_;
 3908:     if ($env{'browser.blackwhite'} eq 'on') {
 3909: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 3910: 	    return '#000000';
 3911: 	}
 3912: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 3913: 	    return '#FFFFFF';
 3914: 	}
 3915: 	if ($which=~/\.tabbg$/) {
 3916: 	    return '#CCCCCC';
 3917: 	}
 3918:     }
 3919:     if (exists($env{'environment.color.'.$which})) {
 3920: 	return $env{'environment.color.'.$which};
 3921:     }
 3922:     $domain=&determinedomain($domain);
 3923:     my %domdesign = &get_domainconf($domain);
 3924:     my $output;
 3925:     if ($domdesign{$domain.'.'.$which} ne '') {
 3926: 	$output = $domdesign{$domain.'.'.$which};
 3927:     } else {
 3928:         $output = $defaultdesign{$which};
 3929:     }
 3930:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 3931:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 3932:         if ($output =~ m{^/(adm|res)/}) {
 3933: 	    if ($output =~ m{^/res/}) {
 3934: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 3935: 		&Apache::lonnet::repcopy($local_name);
 3936: 	    }
 3937:             $output = &lonhttpdurl($output);
 3938:         }
 3939:     }
 3940:     return $output;
 3941: }
 3942: 
 3943: ###############################################
 3944: ###############################################
 3945: 
 3946: =pod
 3947: 
 3948: =back
 3949: 
 3950: =head1 HTML Helpers
 3951: 
 3952: =over 4
 3953: 
 3954: =item * &bodytag()
 3955: 
 3956: Returns a uniform header for LON-CAPA web pages.
 3957: 
 3958: Inputs: 
 3959: 
 3960: =over 4
 3961: 
 3962: =item * $title, A title to be displayed on the page.
 3963: 
 3964: =item * $function, the current role (can be undef).
 3965: 
 3966: =item * $addentries, extra parameters for the <body> tag.
 3967: 
 3968: =item * $bodyonly, if defined, only return the <body> tag.
 3969: 
 3970: =item * $domain, if defined, force a given domain.
 3971: 
 3972: =item * $forcereg, if page should register as content page (relevant for 
 3973:             text interface only)
 3974: 
 3975: =item * $customtitle, alternate text to use instead of $title
 3976:                       in the title box that appears, this text
 3977:                       is not auto translated like the $title is
 3978: 
 3979: =item * $notopbar, if true, keep the 'what is this' info but remove the
 3980:                    navigational links
 3981: 
 3982: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 3983: 
 3984: =item * $notitle, if true keep the nav controls, but remove the title bar
 3985: 
 3986: =item * $no_inline_link, if true and in remote mode, don't show the 
 3987:          'Switch To Inline Menu' link
 3988: 
 3989: =item * $args, optional argument valid values are
 3990:             no_auto_mt_title -> prevents &mt()ing the title arg
 3991:             inherit_jsmath -> when creating popup window in a page,
 3992:                               should it have jsmath forced on by the
 3993:                               current page
 3994: 
 3995: =back
 3996: 
 3997: Returns: A uniform header for LON-CAPA web pages.  
 3998: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 3999: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4000: other decorations will be returned.
 4001: 
 4002: =cut
 4003: 
 4004: sub bodytag {
 4005:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4006: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4007: 
 4008:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4009: 
 4010:     $function = &get_users_function() if (!$function);
 4011:     my $img =    &designparm($function.'.img',$domain);
 4012:     my $font =   &designparm($function.'.font',$domain);
 4013:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4014: 
 4015:     my %design = ( 'style'   => 'margin-top: 0px',
 4016: 		   'bgcolor' => $pgbg,
 4017: 		   'text'    => $font,
 4018:                    'alink'   => &designparm($function.'.alink',$domain),
 4019: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4020: 		   'link'    => &designparm($function.'.link',$domain),);
 4021:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4022: 
 4023:  # role and realm
 4024:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4025:     if ($role  eq 'ca') {
 4026:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4027:         $realm = &plainname($rname,$rdom);
 4028:     } 
 4029: # realm
 4030:     if ($env{'request.course.id'}) {
 4031:         if ($env{'request.role'} !~ /^cr/) {
 4032:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4033:         }
 4034: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4035:     } else {
 4036:         $role = &Apache::lonnet::plaintext($role);
 4037:     }
 4038: 
 4039:     if (!$realm) { $realm='&nbsp;'; }
 4040: # Set messages
 4041:     my $messages=&domainlogo($domain);
 4042: 
 4043:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4044: 
 4045: # construct main body tag
 4046:     my $bodytag = "<body $extra_body_attr>".
 4047: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4048: 
 4049:     if ($bodyonly) {
 4050:         return $bodytag;
 4051:     } elsif ($env{'browser.interface'} eq 'textual') {
 4052: # Accessibility
 4053:           
 4054: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4055: 	if (!$notitle) {
 4056: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4057: 	}
 4058: 	return $bodytag;
 4059:     }
 4060: 
 4061:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4062:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4063: 	undef($role);
 4064:     } else {
 4065: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4066:     }
 4067:     
 4068:     my $roleinfo=(<<ENDROLE);
 4069: <td class="LC_title_bar_who">
 4070: <div class="LC_title_bar_name">
 4071:     $name
 4072:     &nbsp;
 4073: </div>
 4074: <div class="LC_title_bar_role">
 4075: $role&nbsp;
 4076: </div>
 4077: <div class="LC_title_bar_realm">
 4078: $realm&nbsp;
 4079: </div>
 4080: </td>
 4081: ENDROLE
 4082: 
 4083:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4084:     if ($customtitle) {
 4085:         $titleinfo = $customtitle;
 4086:     }
 4087:     #
 4088:     # Extra info if you are the DC
 4089:     my $dc_info = '';
 4090:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4091:                         $env{'course.'.$env{'request.course.id'}.
 4092:                                  '.domain'}.'/'})) {
 4093:         my $cid = $env{'request.course.id'};
 4094:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4095:         $dc_info =~ s/\s+$//;
 4096:         $dc_info = '('.$dc_info.')';
 4097:     }
 4098: 
 4099:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4100:         # No Remote
 4101: 	if ($env{'request.state'} eq 'construct') {
 4102: 	    $forcereg=1;
 4103: 	}
 4104: 
 4105: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4106: 	    # this is for resources; directories have customtitle, and crumbs
 4107:             # and select recent are created in lonpubdir.pm  
 4108: 	    my ($uname,$thisdisfn)=
 4109: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4110: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4111: 	    $formaction=~s/\/+/\//g;
 4112: 
 4113: 	    my $parentpath = '';
 4114: 	    my $lastitem = '';
 4115: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4116: 		$parentpath = $1;
 4117: 		$lastitem = $2;
 4118: 	    } else {
 4119: 		$lastitem = $thisdisfn;
 4120: 	    }
 4121: 	    $titleinfo = 
 4122: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4123: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4124: 		.'<form name="dirs" method="post" action="'.$formaction
 4125: 		.'" target="_top"><tt><b>'
 4126: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4127: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4128: 		.'</form>'
 4129: 		.&Apache::lonmenu::constspaceform();
 4130:         }
 4131: 
 4132:         my $titletable;
 4133: 	if (!$notitle) {
 4134: 	    $titletable =
 4135: 		'<table id="LC_title_bar">'.
 4136:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4137: 			 '</tr></table>';
 4138: 	}
 4139: 	if ($notopbar) {
 4140: 	    $bodytag .= $titletable;
 4141: 	} else {
 4142: 	    if ($env{'request.state'} eq 'construct') {
 4143:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4144: 							  $titletable);
 4145:             } else {
 4146:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4147: 		    $titletable;
 4148:             }
 4149:         }
 4150:         return $bodytag;
 4151:     }
 4152: 
 4153: #
 4154: # Top frame rendering, Remote is up
 4155: #
 4156: 
 4157:     my $imgsrc = $img;
 4158:     if ($img =~ /^\/adm/) {
 4159:         $imgsrc = &lonhttpdurl($img);
 4160:     }
 4161:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4162: 
 4163:     # Explicit link to get inline menu
 4164:     my $menu= ($no_inline_link?''
 4165: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4166:     #
 4167:     if ($notitle) {
 4168: 	return $bodytag;
 4169:     }
 4170:     return(<<ENDBODY);
 4171: $bodytag
 4172: <table id="LC_title_bar" class="LC_with_remote">
 4173: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4174:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4175: </tr>
 4176: <tr><td>$titleinfo $dc_info $menu</td>
 4177: $roleinfo
 4178: </tr>
 4179: </table>
 4180: ENDBODY
 4181: }
 4182: 
 4183: sub make_attr_string {
 4184:     my ($register,$attr_ref) = @_;
 4185: 
 4186:     if ($attr_ref && !ref($attr_ref)) {
 4187: 	die("addentries Must be a hash ref ".
 4188: 	    join(':',caller(1))." ".
 4189: 	    join(':',caller(0))." ");
 4190:     }
 4191: 
 4192:     if ($register) {
 4193: 	my ($on_load,$on_unload);
 4194: 	foreach my $key (keys(%{$attr_ref})) {
 4195: 	    if      (lc($key) eq 'onload') {
 4196: 		$on_load.=$attr_ref->{$key}.';';
 4197: 		delete($attr_ref->{$key});
 4198: 
 4199: 	    } elsif (lc($key) eq 'onunload') {
 4200: 		$on_unload.=$attr_ref->{$key}.';';
 4201: 		delete($attr_ref->{$key});
 4202: 	    }
 4203: 	}
 4204: 	$attr_ref->{'onload'}  =
 4205: 	    &Apache::lonmenu::loadevents().  $on_load;
 4206: 	$attr_ref->{'onunload'}=
 4207: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4208:     }
 4209: 
 4210: # Accessibility font enhance
 4211:     if ($env{'browser.fontenhance'} eq 'on') {
 4212: 	my $style;
 4213: 	foreach my $key (keys(%{$attr_ref})) {
 4214: 	    if (lc($key) eq 'style') {
 4215: 		$style.=$attr_ref->{$key}.';';
 4216: 		delete($attr_ref->{$key});
 4217: 	    }
 4218: 	}
 4219: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4220:     }
 4221: 
 4222:     if ($env{'browser.blackwhite'} eq 'on') {
 4223: 	delete($attr_ref->{'font'});
 4224: 	delete($attr_ref->{'link'});
 4225: 	delete($attr_ref->{'alink'});
 4226: 	delete($attr_ref->{'vlink'});
 4227: 	delete($attr_ref->{'bgcolor'});
 4228: 	delete($attr_ref->{'background'});
 4229:     }
 4230: 
 4231:     my $attr_string;
 4232:     foreach my $attr (keys(%$attr_ref)) {
 4233: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4234:     }
 4235:     return $attr_string;
 4236: }
 4237: 
 4238: 
 4239: ###############################################
 4240: ###############################################
 4241: 
 4242: =pod
 4243: 
 4244: =item * &endbodytag()
 4245: 
 4246: Returns a uniform footer for LON-CAPA web pages.
 4247: 
 4248: Inputs: 1 - optional reference to an args hash
 4249: If in the hash, key for noredirectlink has a value which evaluates to true,
 4250: a 'Continue' link is not displayed if the page contains an
 4251: internal redirect in the <head></head> section,
 4252: i.e., $env{'internal.head.redirect'} exists   
 4253: 
 4254: =cut
 4255: 
 4256: sub endbodytag {
 4257:     my ($args) = @_;
 4258:     my $endbodytag='</body>';
 4259:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4260:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4261:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4262: 	    $endbodytag=
 4263: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4264: 	        &mt('Continue').'</a>'.
 4265: 	        $endbodytag;
 4266:         }
 4267:     }
 4268:     return $endbodytag;
 4269: }
 4270: 
 4271: =pod
 4272: 
 4273: =item * &standard_css()
 4274: 
 4275: Returns a style sheet
 4276: 
 4277: Inputs: (all optional)
 4278:             domain         -> force to color decorate a page for a specific
 4279:                                domain
 4280:             function       -> force usage of a specific rolish color scheme
 4281:             bgcolor        -> override the default page bgcolor
 4282: 
 4283: =cut
 4284: 
 4285: sub standard_css {
 4286:     my ($function,$domain,$bgcolor) = @_;
 4287:     $function  = &get_users_function() if (!$function);
 4288:     my $img    = &designparm($function.'.img',   $domain);
 4289:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4290:     my $font   = &designparm($function.'.font',  $domain);
 4291:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4292:     my $pgbg_or_bgcolor =
 4293: 	         $bgcolor ||
 4294: 	         &designparm($function.'.pgbg',  $domain);
 4295:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4296:     my $alink  = &designparm($function.'.alink', $domain);
 4297:     my $vlink  = &designparm($function.'.vlink', $domain);
 4298:     my $link   = &designparm($function.'.link',  $domain);
 4299: 
 4300:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4301:     my $mono                 = 'monospace';
 4302:     my $data_table_head      = $tabbg;
 4303:     my $data_table_light     = '#EEEEEE';
 4304:     my $data_table_dark      = '#DDDDDD';
 4305:     my $data_table_darker    = '#CCCCCC';
 4306:     my $data_table_highlight = '#FFFF00';
 4307:     my $mail_new             = '#FFBB77';
 4308:     my $mail_new_hover       = '#DD9955';
 4309:     my $mail_read            = '#BBBB77';
 4310:     my $mail_read_hover      = '#999944';
 4311:     my $mail_replied         = '#AAAA88';
 4312:     my $mail_replied_hover   = '#888855';
 4313:     my $mail_other           = '#99BBBB';
 4314:     my $mail_other_hover     = '#669999';
 4315:     my $table_header         = '#DDDDDD';
 4316:     my $feedback_link_bg     = '#BBBBBB';
 4317: 
 4318:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4319: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4320: 	                                                 : '0px 3px 0px 4px';
 4321: 
 4322: 
 4323:     return <<END;
 4324: h1, h2, h3, th { font-family: $sans }
 4325: a:focus { color: red; background: yellow } 
 4326: table.thinborder,
 4327: 
 4328: table.thinborder tr th {
 4329:   border-style: solid;
 4330:   border-width: 1px;
 4331:   background: $tabbg;
 4332: }
 4333: table.thinborder tr td {
 4334:   border-style: solid;
 4335:   border-width: 1px
 4336: }
 4337: 
 4338: form, .inline { display: inline; }
 4339: .center { text-align: center; }
 4340: .LC_filename {font-family: $mono; white-space:pre;}
 4341: .LC_error {
 4342:   color: red;
 4343:   font-size: larger;
 4344: }
 4345: .LC_warning,
 4346: .LC_diff_removed {
 4347:   color: red;
 4348: }
 4349: 
 4350: .LC_info,
 4351: .LC_success,
 4352: .LC_diff_added {
 4353:   color: green;
 4354: }
 4355: .LC_unknown {
 4356:   color: yellow;
 4357: }
 4358: 
 4359: .LC_icon {
 4360:   border: 0px;
 4361: }
 4362: .LC_indexer_icon {
 4363:   border: 0px;
 4364:   height: 22px;
 4365: }
 4366: .LC_docs_spacer {
 4367:   width: 25px;
 4368:   height: 1px;
 4369:   border: 0px;
 4370: }
 4371: 
 4372: .LC_internal_info {
 4373:   color: #999;
 4374: }
 4375: 
 4376: table.LC_pastsubmission {
 4377:   border: 1px solid black;
 4378:   margin: 2px;
 4379: }
 4380: 
 4381: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4382:   width: 100%;
 4383:   background: $pgbg;
 4384:   border: 2px;
 4385:   border-collapse: separate;
 4386:   padding: 0px;
 4387: }
 4388: 
 4389: table#LC_title_bar, table.LC_breadcrumbs, 
 4390: table#LC_title_bar.LC_with_remote {
 4391:   width: 100%;
 4392:   border-color: $pgbg;
 4393:   border-style: solid;
 4394:   border-width: $border;
 4395: 
 4396:   background: $pgbg;
 4397:   font-family: $sans;
 4398:   border-collapse: collapse;
 4399:   padding: 0px;
 4400: }
 4401: 
 4402: table.LC_docs_path {
 4403:   width: 100%;
 4404:   border: 0;
 4405:   background: $pgbg;
 4406:   font-family: $sans;
 4407:   border-collapse: collapse;
 4408:   padding: 0px;
 4409: }
 4410: 
 4411: table#LC_title_bar td {
 4412:   background: $tabbg;
 4413: }
 4414: table#LC_title_bar td.LC_title_bar_who {
 4415:   background: $tabbg;
 4416:   color: $font;
 4417:   font: small $sans;
 4418:   text-align: right;
 4419: }
 4420: span.LC_metadata {
 4421:     font-family: $sans;
 4422: }
 4423: span.LC_title_bar_title {
 4424:   font: bold x-large $sans;
 4425: }
 4426: table#LC_title_bar td.LC_title_bar_domain_logo {
 4427:   background: $sidebg;
 4428:   text-align: right;
 4429:   padding: 0px;
 4430: }
 4431: table#LC_title_bar td.LC_title_bar_role_logo {
 4432:   background: $sidebg;
 4433:   padding: 0px;
 4434: }
 4435: 
 4436: table#LC_menubuttons_mainmenu {
 4437:   width: 100%;
 4438:   border: 0px;
 4439:   border-spacing: 1px;
 4440:   padding: 0px 1px;
 4441:   margin: 0px;
 4442:   border-collapse: separate;
 4443: }
 4444: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4445:   border: 0px;
 4446: }
 4447: table#LC_top_nav td {
 4448:   background: $tabbg;
 4449:   border: 0px;
 4450:   font-size: small;
 4451: }
 4452: table#LC_top_nav td a, div#LC_top_nav a {
 4453:   color: $font;
 4454:   font-family: $sans;
 4455: }
 4456: table#LC_top_nav td.LC_top_nav_logo {
 4457:   background: $tabbg;
 4458:   text-align: left;
 4459:   white-space: nowrap;
 4460:   width: 31px;
 4461: }
 4462: table#LC_top_nav td.LC_top_nav_logo img {
 4463:   border: 0px;
 4464:   vertical-align: bottom;
 4465: }
 4466: table#LC_top_nav td.LC_top_nav_exit,
 4467: table#LC_top_nav td.LC_top_nav_help {
 4468:   width: 2.0em;
 4469: }
 4470: table#LC_top_nav td.LC_top_nav_login {
 4471:   width: 4.0em;
 4472:   text-align: center;
 4473: }
 4474: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4475:   background: $tabbg;
 4476:   color: $font;
 4477:   font-family: $sans;
 4478:   font-size: smaller;
 4479: }
 4480: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4481: table.LC_docs_path td.LC_docs_path_component {
 4482:   background: $tabbg;
 4483:   color: $font;
 4484:   font-family: $sans;
 4485:   font-size: larger;
 4486:   text-align: right;
 4487: }
 4488: td.LC_table_cell_checkbox {
 4489:   text-align: center;
 4490: }
 4491: 
 4492: table#LC_mainmenu td.LC_mainmenu_column {
 4493:     vertical-align: top;
 4494: }
 4495: 
 4496: .LC_menubuttons_inline_text {
 4497:   color: $font;
 4498:   font-family: $sans;
 4499:   font-size: smaller;
 4500: }
 4501: 
 4502: .LC_menubuttons_link {
 4503:   text-decoration: none;
 4504: }
 4505: 
 4506: .LC_menubuttons_category {
 4507:   color: $font;
 4508:   background: $pgbg;
 4509:   font-family: $sans;
 4510:   font-size: larger;
 4511:   font-weight: bold;
 4512: }
 4513: 
 4514: td.LC_menubuttons_text {
 4515:   width: 90%;
 4516:   color: $font;
 4517:   font-family: $sans;
 4518: }
 4519: 
 4520: td.LC_menubuttons_img {
 4521: }
 4522: 
 4523: .LC_current_location {
 4524:   font-family: $sans;
 4525:   background: $tabbg;
 4526: }
 4527: .LC_new_mail {
 4528:   font-family: $sans;
 4529:   background: $tabbg;
 4530:   font-weight: bold;
 4531: }
 4532: 
 4533: .LC_rolesmenu_is {
 4534:   font-family: $sans;
 4535: }
 4536: 
 4537: .LC_rolesmenu_selected {
 4538:   font-family: $sans;
 4539: }
 4540: 
 4541: .LC_rolesmenu_future {
 4542:   font-family: $sans;
 4543: }
 4544: 
 4545: 
 4546: .LC_rolesmenu_will {
 4547:   font-family: $sans;
 4548: }
 4549: 
 4550: .LC_rolesmenu_will_not {
 4551:   font-family: $sans;
 4552: }
 4553: 
 4554: .LC_rolesmenu_expired {
 4555:   font-family: $sans;
 4556: }
 4557: 
 4558: .LC_rolesinfo {
 4559:   font-family: $sans;
 4560: }
 4561: 
 4562: .LC_dropadd_labeltext {
 4563:   font-family: $sans;
 4564:   text-align: right;
 4565: }
 4566: 
 4567: .LC_preferences_labeltext {
 4568:   font-family: $sans;
 4569:   text-align: right;
 4570: }
 4571: 
 4572: table.LC_aboutme_port {
 4573:   border: 0px;
 4574:   border-collapse: collapse;
 4575:   border-spacing: 0px;
 4576: }
 4577: table.LC_data_table, table.LC_mail_list {
 4578:   border: 1px solid #000000;
 4579:   border-collapse: separate;
 4580:   border-spacing: 1px;
 4581:   background: $pgbg;
 4582: }
 4583: .LC_data_table_dense {
 4584:   font-size: small;
 4585: }
 4586: table.LC_nested_outer {
 4587:   border: 1px solid #000000;
 4588:   border-collapse: collapse;
 4589:   border-spacing: 0px;
 4590:   width: 100%;
 4591: }
 4592: table.LC_nested {
 4593:   border: 0px;
 4594:   border-collapse: collapse;
 4595:   border-spacing: 0px;
 4596:   width: 100%;
 4597: }
 4598: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4599: table.LC_prior_tries tr th {
 4600:   font-weight: bold;
 4601:   background-color: $data_table_head;
 4602:   font-size: smaller;
 4603: }
 4604: table.LC_data_table tr.LC_odd_row > td, 
 4605: table.LC_aboutme_port tr td {
 4606:   background-color: $data_table_light;
 4607:   padding: 2px;
 4608: }
 4609: table.LC_data_table tr.LC_even_row > td,
 4610: table.LC_aboutme_port tr.LC_even_row td {
 4611:   background-color: $data_table_dark;
 4612: }
 4613: table.LC_data_table tr.LC_data_table_highlight td {
 4614:   background-color: $data_table_darker;
 4615: }
 4616: table.LC_data_table tr td.LC_leftcol_header {
 4617:   background-color: $data_table_head;
 4618:   font-weight: bold;
 4619: }
 4620: table.LC_data_table tr.LC_empty_row td,
 4621: table.LC_nested tr.LC_empty_row td {
 4622:   background-color: #FFFFFF;
 4623:   font-weight: bold;
 4624:   font-style: italic;
 4625:   text-align: center;
 4626:   padding: 8px;
 4627: }
 4628: table.LC_nested tr.LC_empty_row td {
 4629:   padding: 4ex
 4630: }
 4631: table.LC_nested_outer tr th {
 4632:   font-weight: bold;
 4633:   background-color: $data_table_head;
 4634:   font-size: smaller;
 4635:   border-bottom: 1px solid #000000;
 4636: }
 4637: table.LC_nested_outer tr td.LC_subheader {
 4638:   background-color: $data_table_head;
 4639:   font-weight: bold;
 4640:   font-size: small;
 4641:   border-bottom: 1px solid #000000;
 4642:   text-align: right;
 4643: }
 4644: table.LC_nested tr.LC_info_row td {
 4645:   background-color: #CCC;
 4646:   font-weight: bold;
 4647:   font-size: small;
 4648:   text-align: center;
 4649: }
 4650: table.LC_nested tr.LC_info_row td.LC_left_item,
 4651: table.LC_nested_outer tr th.LC_left_item {
 4652:   text-align: left;
 4653: }
 4654: table.LC_nested td {
 4655:   background-color: #FFF;
 4656:   font-size: small;
 4657: }
 4658: table.LC_nested_outer tr th.LC_right_item,
 4659: table.LC_nested tr.LC_info_row td.LC_right_item,
 4660: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4661: table.LC_nested tr td.LC_right_item {
 4662:   text-align: right;
 4663: }
 4664: 
 4665: table.LC_nested tr.LC_odd_row td {
 4666:   background-color: #EEE;
 4667: }
 4668: 
 4669: table.LC_createuser {
 4670: }
 4671: 
 4672: table.LC_createuser tr.LC_section_row td {
 4673:   font-size: smaller;
 4674: }
 4675: 
 4676: table.LC_createuser tr.LC_info_row td  {
 4677:   background-color: #CCC;
 4678:   font-weight: bold;
 4679:   text-align: center;
 4680: }
 4681: 
 4682: table.LC_calendar {
 4683:   border: 1px solid #000000;
 4684:   border-collapse: collapse;
 4685: }
 4686: table.LC_calendar_pickdate {
 4687:   font-size: xx-small;
 4688: }
 4689: table.LC_calendar tr td {
 4690:   border: 1px solid #000000;
 4691:   vertical-align: top;
 4692: }
 4693: table.LC_calendar tr td.LC_calendar_day_empty {
 4694:   background-color: $data_table_dark;
 4695: }
 4696: table.LC_calendar tr td.LC_calendar_day_current {
 4697:   background-color: $data_table_highlight;
 4698: }
 4699: 
 4700: table.LC_mail_list tr.LC_mail_new {
 4701:   background-color: $mail_new;
 4702: }
 4703: table.LC_mail_list tr.LC_mail_new:hover {
 4704:   background-color: $mail_new_hover;
 4705: }
 4706: table.LC_mail_list tr.LC_mail_read {
 4707:   background-color: $mail_read;
 4708: }
 4709: table.LC_mail_list tr.LC_mail_read:hover {
 4710:   background-color: $mail_read_hover;
 4711: }
 4712: table.LC_mail_list tr.LC_mail_replied {
 4713:   background-color: $mail_replied;
 4714: }
 4715: table.LC_mail_list tr.LC_mail_replied:hover {
 4716:   background-color: $mail_replied_hover;
 4717: }
 4718: table.LC_mail_list tr.LC_mail_other {
 4719:   background-color: $mail_other;
 4720: }
 4721: table.LC_mail_list tr.LC_mail_other:hover {
 4722:   background-color: $mail_other_hover;
 4723: }
 4724: table.LC_mail_list tr.LC_mail_even {
 4725: }
 4726: table.LC_mail_list tr.LC_mail_odd {
 4727: }
 4728: 
 4729: 
 4730: table#LC_portfolio_actions {
 4731:   width: auto;
 4732:   background: $pgbg;
 4733:   border: 0px;
 4734:   border-spacing: 2px 2px;
 4735:   padding: 0px;
 4736:   margin: 0px;
 4737:   border-collapse: separate;
 4738: }
 4739: table#LC_portfolio_actions td.LC_label {
 4740:   background: $tabbg;
 4741:   text-align: right;
 4742: }
 4743: table#LC_portfolio_actions td.LC_value {
 4744:   background: $tabbg;
 4745: }
 4746: 
 4747: table#LC_cstr_controls {
 4748:   width: 100%;
 4749:   border-collapse: collapse;
 4750: }
 4751: table#LC_cstr_controls tr td {
 4752:   border: 4px solid $pgbg;
 4753:   padding: 4px;
 4754:   text-align: center;
 4755:   background: $tabbg;
 4756: }
 4757: table#LC_cstr_controls tr th {
 4758:   border: 4px solid $pgbg;
 4759:   background: $table_header;
 4760:   text-align: center;
 4761:   font-family: $sans;
 4762:   font-size: smaller;
 4763: }
 4764: 
 4765: table#LC_browser {
 4766:  
 4767: }
 4768: table#LC_browser tr th {
 4769:   background: $table_header;
 4770: }
 4771: table#LC_browser tr td {
 4772:   padding: 2px;
 4773: }
 4774: table#LC_browser tr.LC_browser_file,
 4775: table#LC_browser tr.LC_browser_file_published {
 4776:   background: #CCFF88;
 4777: }
 4778: table#LC_browser tr.LC_browser_file_locked,
 4779: table#LC_browser tr.LC_browser_file_unpublished {
 4780:   background: #FFAA99;
 4781: }
 4782: table#LC_browser tr.LC_browser_file_obsolete {
 4783:   background: #AAAAAA;
 4784: }
 4785: table#LC_browser tr.LC_browser_file_modified,
 4786: table#LC_browser tr.LC_browser_file_metamodified {
 4787:   background: #FFFF77;
 4788: }
 4789: table#LC_browser tr.LC_browser_folder {
 4790:   background: #CCCCFF;
 4791: }
 4792: span.LC_current_location {
 4793:   font-size: x-large;
 4794:   background: $pgbg;
 4795: }
 4796: 
 4797: span.LC_parm_menu_item {
 4798:   font-size: larger;
 4799:   font-family: $sans;
 4800: }
 4801: span.LC_parm_scope_all {
 4802:   color: red;
 4803: }
 4804: span.LC_parm_scope_folder {
 4805:   color: green;
 4806: }
 4807: span.LC_parm_scope_resource {
 4808:   color: orange;
 4809: }
 4810: span.LC_parm_part {
 4811:   color: blue;
 4812: }
 4813: span.LC_parm_folder, span.LC_parm_symb {
 4814:   font-size: x-small;
 4815:   font-family: $mono;
 4816:   color: #AAAAAA;
 4817: }
 4818: 
 4819: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4820: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4821:   border: 1px solid black;
 4822:   border-collapse: collapse;
 4823: }
 4824: table.LC_parm_overview_restrictions td {
 4825:   border-width: 1px 4px 1px 4px;
 4826:   border-style: solid;
 4827:   border-color: $pgbg;
 4828:   text-align: center;
 4829: }
 4830: table.LC_parm_overview_restrictions th {
 4831:   background: $tabbg;
 4832:   border-width: 1px 4px 1px 4px;
 4833:   border-style: solid;
 4834:   border-color: $pgbg;
 4835: }
 4836: table#LC_helpmenu {
 4837:   border: 0px;
 4838:   height: 55px;
 4839:   border-spacing: 0px;
 4840: }
 4841: 
 4842: table#LC_helpmenu fieldset legend {
 4843:   font-size: larger;
 4844:   font-weight: bold;
 4845: }
 4846: table#LC_helpmenu_links {
 4847:   width: 100%;
 4848:   border: 1px solid black;
 4849:   background: $pgbg;
 4850:   padding: 0px;
 4851:   border-spacing: 1px;
 4852: }
 4853: table#LC_helpmenu_links tr td {
 4854:   padding: 1px;
 4855:   background: $tabbg;
 4856:   text-align: center;
 4857:   font-weight: bold;
 4858: }
 4859: 
 4860: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 4861: table#LC_helpmenu_links a:active {
 4862:   text-decoration: none;
 4863:   color: $font;
 4864: }
 4865: table#LC_helpmenu_links a:hover {
 4866:   text-decoration: underline;
 4867:   color: $vlink;
 4868: }
 4869: 
 4870: .LC_chrt_popup_exists {
 4871:   border: 1px solid #339933;
 4872:   margin: -1px;
 4873: }
 4874: .LC_chrt_popup_up {
 4875:   border: 1px solid yellow;
 4876:   margin: -1px;
 4877: }
 4878: .LC_chrt_popup {
 4879:   border: 1px solid #8888FF;
 4880:   background: #CCCCFF;
 4881: }
 4882: table.LC_pick_box {
 4883:   border-collapse: separate;
 4884:   background: white;
 4885:   border: 1px solid black;
 4886:   border-spacing: 1px;
 4887: }
 4888: table.LC_pick_box td.LC_pick_box_title {
 4889:   background: $tabbg;
 4890:   font-weight: bold;
 4891:   text-align: right;
 4892:   width: 184px;
 4893:   padding: 8px;
 4894: }
 4895: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 4896:   background: $tabbg;
 4897:   font-weight: bold;
 4898:   text-align: right;
 4899:   width: 350px;
 4900:   padding: 8px;
 4901: }
 4902: 
 4903: table.LC_pick_box td.LC_pick_box_value {
 4904:   text-align: left;
 4905:   padding: 8px;
 4906: }
 4907: table.LC_pick_box td.LC_pick_box_select {
 4908:   text-align: left;
 4909:   padding: 8px;
 4910: }
 4911: table.LC_pick_box td.LC_pick_box_separator {
 4912:   padding: 0px;
 4913:   height: 1px;
 4914:   background: black;
 4915: }
 4916: table.LC_pick_box td.LC_pick_box_submit {
 4917:   text-align: right;
 4918: }
 4919: table.LC_pick_box td.LC_evenrow_value {
 4920:   text-align: left;
 4921:   padding: 8px;
 4922:   background-color: $data_table_light;
 4923: }
 4924: table.LC_pick_box td.LC_oddrow_value {
 4925:   text-align: left;
 4926:   padding: 8px;
 4927:   background-color: $data_table_light;
 4928: }
 4929: table.LC_helpform_receipt {
 4930:   width: 620px;
 4931:   border-collapse: separate;
 4932:   background: white;
 4933:   border: 1px solid black;
 4934:   border-spacing: 1px;
 4935: }
 4936: table.LC_helpform_receipt td.LC_pick_box_title {
 4937:   background: $tabbg;
 4938:   font-weight: bold;
 4939:   text-align: right;
 4940:   width: 184px;
 4941:   padding: 8px;
 4942: }
 4943: table.LC_helpform_receipt td.LC_evenrow_value {
 4944:   text-align: left;
 4945:   padding: 8px;
 4946:   background-color: $data_table_light;
 4947: }
 4948: table.LC_helpform_receipt td.LC_oddrow_value {
 4949:   text-align: left;
 4950:   padding: 8px;
 4951:   background-color: $data_table_light;
 4952: }
 4953: table.LC_helpform_receipt td.LC_pick_box_separator {
 4954:   padding: 0px;
 4955:   height: 1px;
 4956:   background: black;
 4957: }
 4958: span.LC_helpform_receipt_cat {
 4959:   font-weight: bold;
 4960: }
 4961: table.LC_group_priv_box {
 4962:   background: white;
 4963:   border: 1px solid black;
 4964:   border-spacing: 1px;
 4965: }
 4966: table.LC_group_priv_box td.LC_pick_box_title {
 4967:   background: $tabbg;
 4968:   font-weight: bold;
 4969:   text-align: right;
 4970:   width: 184px;
 4971: }
 4972: table.LC_group_priv_box td.LC_groups_fixed {
 4973:   background: $data_table_light;
 4974:   text-align: center;
 4975: }
 4976: table.LC_group_priv_box td.LC_groups_optional {
 4977:   background: $data_table_dark;
 4978:   text-align: center;
 4979: }
 4980: table.LC_group_priv_box td.LC_groups_functionality {
 4981:   background: $data_table_darker;
 4982:   text-align: center;
 4983:   font-weight: bold;
 4984: }
 4985: table.LC_group_priv td {
 4986:   text-align: left;
 4987:   padding: 0px;
 4988: }
 4989: 
 4990: table.LC_notify_front_page {
 4991:   background: white;
 4992:   border: 1px solid black;
 4993:   padding: 8px;
 4994: }
 4995: table.LC_notify_front_page td {
 4996:   padding: 8px;
 4997: }
 4998: .LC_navbuttons {
 4999:   margin: 2ex 0ex 2ex 0ex;
 5000: }
 5001: .LC_topic_bar {
 5002:   font-family: $sans;
 5003:   font-weight: bold;
 5004:   width: 100%;
 5005:   background: $tabbg;
 5006:   vertical-align: middle;
 5007:   margin: 2ex 0ex 2ex 0ex;
 5008: }
 5009: .LC_topic_bar span {
 5010:   vertical-align: middle;
 5011: }
 5012: .LC_topic_bar img {
 5013:   vertical-align: bottom;
 5014: }
 5015: table.LC_course_group_status {
 5016:   margin: 20px;
 5017: }
 5018: table.LC_status_selector td {
 5019:   vertical-align: top;
 5020:   text-align: center;
 5021:   padding: 4px;
 5022: }
 5023: table.LC_descriptive_input td.LC_description {
 5024:   vertical-align: top;
 5025:   text-align: right;
 5026:   font-weight: bold;
 5027: }
 5028: div.LC_feedback_link {
 5029:   clear: both;
 5030:   background: white;
 5031:   width: 100%;  
 5032: }
 5033: span.LC_feedback_link {
 5034:   background: $feedback_link_bg;
 5035:   font-size: larger;
 5036: }
 5037: span.LC_message_link {
 5038:   background: $feedback_link_bg;
 5039:   font-size: larger;
 5040:   position: absolute;
 5041:   right: 1em;
 5042: }
 5043: 
 5044: table.LC_prior_tries {
 5045:   border: 1px solid #000000;
 5046:   border-collapse: separate;
 5047:   border-spacing: 1px;
 5048: }
 5049: 
 5050: table.LC_prior_tries td {
 5051:   padding: 2px;
 5052: }
 5053: 
 5054: .LC_answer_correct {
 5055:   background: #AAFFAA;
 5056:   color: black;
 5057: }
 5058: .LC_answer_charged_try {
 5059:   background: #FFAAAA ! important;
 5060:   color: black;
 5061: }
 5062: .LC_answer_not_charged_try, 
 5063: .LC_answer_no_grade,
 5064: .LC_answer_late {
 5065:   background: #FFFFAA;
 5066:   color: black;
 5067: }
 5068: .LC_answer_previous {
 5069:   background: #AAAAFF;
 5070:   color: black;
 5071: }
 5072: .LC_answer_no_message {
 5073:   background: #FFFFFF;
 5074:   color: black;
 5075: }
 5076: .LC_answer_unknown {
 5077:   background: orange;
 5078:   color: black;
 5079: }
 5080: 
 5081: 
 5082: span.LC_prior_numerical,
 5083: span.LC_prior_string,
 5084: span.LC_prior_custom,
 5085: span.LC_prior_reaction,
 5086: span.LC_prior_math {
 5087:   font-family: monospace;
 5088:   white-space: pre;
 5089: }
 5090: 
 5091: span.LC_prior_string {
 5092:   font-family: monospace;
 5093:   white-space: pre;
 5094: }
 5095: 
 5096: table.LC_prior_option {
 5097:   width: 100%;
 5098:   border-collapse: collapse;
 5099: }
 5100: table.LC_prior_rank, table.LC_prior_match {
 5101:   border-collapse: collapse;
 5102: }
 5103: table.LC_prior_option tr td,
 5104: table.LC_prior_rank tr td,
 5105: table.LC_prior_match tr td {
 5106:   border: 1px solid #000000;
 5107: }
 5108: 
 5109: span.LC_nobreak {
 5110:   white-space: nowrap;
 5111: }
 5112: 
 5113: span.LC_cusr_emph {
 5114:   font-style: italic;
 5115: }
 5116: 
 5117: span.LC_cusr_subheading {
 5118:   font-weight: normal;
 5119:   font-size: 85%;
 5120: }
 5121: 
 5122: table.LC_docs_documents {
 5123:   background: #BBBBBB;
 5124:   border-width: 0px;
 5125:   border-collapse: collapse;
 5126: }
 5127: 
 5128: table.LC_docs_documents td.LC_docs_document {
 5129:   border: 2px solid black;
 5130:   padding: 4px;
 5131: }
 5132: 
 5133: .LC_docs_course_commands div {
 5134:   float: left;
 5135:   border: 4px solid #AAAAAA;
 5136:   padding: 4px;
 5137:   background: #DDDDCC;
 5138: }
 5139: 
 5140: .LC_docs_entry_move {
 5141:   border: 0px;
 5142:   border-collapse: collapse;
 5143: }
 5144: 
 5145: .LC_docs_entry_move td {
 5146:   border: 2px solid #BBBBBB;
 5147:   background: #DDDDDD;
 5148: }
 5149: 
 5150: .LC_docs_editor td.LC_docs_entry_commands {
 5151:   background: #DDDDDD;
 5152:   font-size: x-small;
 5153: }
 5154: .LC_docs_copy {
 5155:   color: #000099;
 5156: }
 5157: .LC_docs_cut {
 5158:   color: #550044;
 5159: }
 5160: .LC_docs_rename {
 5161:   color: #009900;
 5162: }
 5163: .LC_docs_remove {
 5164:   color: #990000;
 5165: }
 5166: 
 5167: .LC_docs_reinit_warn,
 5168: .LC_docs_ext_edit {
 5169:   font-size: x-small;
 5170: }
 5171: 
 5172: .LC_docs_editor td.LC_docs_entry_title,
 5173: .LC_docs_editor td.LC_docs_entry_icon {
 5174:   background: #FFFFBB;
 5175: }
 5176: .LC_docs_editor td.LC_docs_entry_parameter {
 5177:   background: #BBBBFF;
 5178:   font-size: x-small;
 5179:   white-space: nowrap;
 5180: }
 5181: 
 5182: table.LC_docs_adddocs td,
 5183: table.LC_docs_adddocs th {
 5184:   border: 1px solid #BBBBBB;
 5185:   padding: 4px;
 5186:   background: #DDDDDD;
 5187: }
 5188: 
 5189: table.LC_sty_begin {
 5190:   background: #BBFFBB;
 5191: }
 5192: table.LC_sty_end {
 5193:   background: #FFBBBB;
 5194: }
 5195: 
 5196: table.LC_double_column {
 5197:   border-width: 0px;
 5198:   border-collapse: collapse;
 5199:   width: 100%;
 5200:   padding: 2px;
 5201: }
 5202: 
 5203: table.LC_double_column tr td.LC_left_col {
 5204:   top: 2px;
 5205:   left: 2px;
 5206:   width: 47%;
 5207:   vertical-align: top;
 5208: }
 5209: 
 5210: table.LC_double_column tr td.LC_right_col {
 5211:   top: 2px;
 5212:   right: 2px; 
 5213:   width: 47%;
 5214:   vertical-align: top;
 5215: }
 5216: 
 5217: span.LC_role_level {
 5218:   font-weight: bold;
 5219: }
 5220: 
 5221: div.LC_left_float {
 5222:   float: left;
 5223:   padding-right: 5%;
 5224:   padding-bottom: 4px;
 5225: }
 5226: 
 5227: div.LC_clear_float_header {
 5228:   padding-bottom: 2px;
 5229: }
 5230: 
 5231: div.LC_clear_float_footer {
 5232:   padding-top: 10px;
 5233:   clear: both;
 5234: }
 5235: 
 5236: 
 5237: div.LC_grade_select_mode {
 5238:   font-family: $sans;
 5239: }
 5240: div.LC_grade_select_mode div div {
 5241:   margin: 5px;
 5242: }
 5243: div.LC_grade_select_mode_selector {
 5244:   margin: 5px;
 5245:   float: left;
 5246: }
 5247: div.LC_grade_select_mode_selector_header {
 5248:   font: bold medium $sans;
 5249: }
 5250: div.LC_grade_select_mode_type {
 5251:   clear: left;
 5252: }
 5253: 
 5254: div.LC_grade_show_user {
 5255:   margin-top: 20px;
 5256:   border: 1px solid black;
 5257: }
 5258: div.LC_grade_user_name {
 5259:   background: #DDDDEE;
 5260:   border-bottom: 1px solid black;
 5261:   font: bold large $sans;
 5262: }
 5263: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5264:   background: #DDEEDD;
 5265: }
 5266: 
 5267: div.LC_grade_show_problem,
 5268: div.LC_grade_submissions,
 5269: div.LC_grade_message_center,
 5270: div.LC_grade_info_links,
 5271: div.LC_grade_assign {
 5272:   margin: 5px;
 5273:   width: 99%;
 5274:   background: #FFFFFF;
 5275: }
 5276: div.LC_grade_show_problem_header,
 5277: div.LC_grade_submissions_header,
 5278: div.LC_grade_message_center_header,
 5279: div.LC_grade_assign_header {
 5280:   font: bold large $sans;
 5281: }
 5282: div.LC_grade_show_problem_problem,
 5283: div.LC_grade_submissions_body,
 5284: div.LC_grade_message_center_body,
 5285: div.LC_grade_assign_body {
 5286:   border: 1px solid black;
 5287:   width: 99%;
 5288:   background: #FFFFFF;
 5289: }
 5290: span.LC_grade_check_note {
 5291:   font: normal medium $sans;
 5292:   display: inline;
 5293:   position: absolute;
 5294:   right: 1em;
 5295: }
 5296: 
 5297: table.LC_scantron_action {
 5298:   width: 100%;
 5299: }
 5300: table.LC_scantron_action tr th {
 5301:   font: normal bold $sans;
 5302: }
 5303: 
 5304: div.LC_edit_problem_header, 
 5305: div.LC_edit_problem_footer {
 5306:   font: normal medium $sans;
 5307:   margin: 2px;
 5308: }
 5309: div.LC_edit_problem_header,
 5310: div.LC_edit_problem_header div,
 5311: div.LC_edit_problem_footer,
 5312: div.LC_edit_problem_footer div,
 5313: div.LC_edit_problem_editxml_header,
 5314: div.LC_edit_problem_editxml_header div {
 5315:   margin-top: 5px;
 5316: }
 5317: div.LC_edit_problem_header_edit_row {
 5318:   background: $tabbg;
 5319:   padding: 3px;
 5320:   margin-bottom: 5px;
 5321: }
 5322: div.LC_edit_problem_header_title {
 5323:   font: larger bold $sans;
 5324:   background: $tabbg;
 5325:   padding: 3px;
 5326: }
 5327: table.LC_edit_problem_header_title {
 5328:   font: larger bold $sans;
 5329:   width: 100%;
 5330:   border-color: $pgbg;
 5331:   border-style: solid;
 5332:   border-width: $border;
 5333: 
 5334:   background: $tabbg;
 5335:   border-collapse: collapse;
 5336:   padding: 0px
 5337: }
 5338: 
 5339: div.LC_edit_problem_discards {
 5340:   float: left;
 5341:   padding-bottom: 5px;
 5342: }
 5343: div.LC_edit_problem_saves {
 5344:   float: right;
 5345:   padding-bottom: 5px;
 5346: }
 5347: hr.LC_edit_problem_divide {
 5348:   clear: both;
 5349:   color: $tabbg;
 5350:   background-color: $tabbg;
 5351:   height: 3px;
 5352:   border: 0px;
 5353: }
 5354: END
 5355: }
 5356: 
 5357: =pod
 5358: 
 5359: =item * &headtag()
 5360: 
 5361: Returns a uniform footer for LON-CAPA web pages.
 5362: 
 5363: Inputs: $title - optional title for the head
 5364:         $head_extra - optional extra HTML to put inside the <head>
 5365:         $args - optional arguments
 5366:             force_register - if is true call registerurl so the remote is 
 5367:                              informed
 5368:             redirect       -> array ref of
 5369:                                    1- seconds before redirect occurs
 5370:                                    2- url to redirect to
 5371:                                    3- whether the side effect should occur
 5372:                            (side effect of setting 
 5373:                                $env{'internal.head.redirect'} to the url 
 5374:                                redirected too)
 5375:             domain         -> force to color decorate a page for a specific
 5376:                                domain
 5377:             function       -> force usage of a specific rolish color scheme
 5378:             bgcolor        -> override the default page bgcolor
 5379:             no_auto_mt_title
 5380:                            -> prevent &mt()ing the title arg
 5381: 
 5382: =cut
 5383: 
 5384: sub headtag {
 5385:     my ($title,$head_extra,$args) = @_;
 5386:     
 5387:     my $function = $args->{'function'} || &get_users_function();
 5388:     my $domain   = $args->{'domain'}   || &determinedomain();
 5389:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5390:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5391: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5392: 		   #time(),
 5393: 		   $env{'environment.color.timestamp'},
 5394: 		   $function,$domain,$bgcolor);
 5395: 
 5396:     $url = '/adm/css/'.&escape($url).'.css';
 5397: 
 5398:     my $result =
 5399: 	'<head>'.
 5400: 	&font_settings();
 5401: 
 5402:     if (!$args->{'frameset'}) {
 5403: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5404:     }
 5405:     if ($args->{'force_register'}) {
 5406: 	$result .= &Apache::lonmenu::registerurl(1);
 5407:     }
 5408:     if (!$args->{'no_nav_bar'} 
 5409: 	&& !$args->{'only_body'}
 5410: 	&& !$args->{'frameset'}) {
 5411: 	$result .= &help_menu_js();
 5412:     }
 5413: 
 5414:     if (ref($args->{'redirect'})) {
 5415: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5416: 	$url = &Apache::lonenc::check_encrypt($url);
 5417: 	if (!$inhibit_continue) {
 5418: 	    $env{'internal.head.redirect'} = $url;
 5419: 	}
 5420: 	$result.=<<ADDMETA
 5421: <meta http-equiv="pragma" content="no-cache" />
 5422: <meta http-equiv="Refresh" content="$time; url=$url" />
 5423: ADDMETA
 5424:     }
 5425:     if (!defined($title)) {
 5426: 	$title = 'The LearningOnline Network with CAPA';
 5427:     }
 5428:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5429:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5430: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5431: 	.$head_extra;
 5432:     return $result;
 5433: }
 5434: 
 5435: =pod
 5436: 
 5437: =item * &font_settings()
 5438: 
 5439: Returns neccessary <meta> to set the proper encoding
 5440: 
 5441: Inputs: none
 5442: 
 5443: =cut
 5444: 
 5445: sub font_settings {
 5446:     my $headerstring='';
 5447:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5448: 	$headerstring.=
 5449: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5450:     }
 5451:     return $headerstring;
 5452: }
 5453: 
 5454: =pod
 5455: 
 5456: =item * &xml_begin()
 5457: 
 5458: Returns the needed doctype and <html>
 5459: 
 5460: Inputs: none
 5461: 
 5462: =cut
 5463: 
 5464: sub xml_begin {
 5465:     my $output='';
 5466: 
 5467:     if ($env{'internal.start_page'}==1) {
 5468: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5469:     }
 5470: 
 5471:     if ($env{'browser.mathml'}) {
 5472: 	$output='<?xml version="1.0"?>'
 5473:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5474: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5475:             
 5476: #	    .'<!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">] >'
 5477: 	    .'<!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">'
 5478:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5479: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5480:     } else {
 5481: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 5482:     }
 5483:     return $output;
 5484: }
 5485: 
 5486: =pod
 5487: 
 5488: =item * &endheadtag()
 5489: 
 5490: Returns a uniform </head> for LON-CAPA web pages.
 5491: 
 5492: Inputs: none
 5493: 
 5494: =cut
 5495: 
 5496: sub endheadtag {
 5497:     return '</head>';
 5498: }
 5499: 
 5500: =pod
 5501: 
 5502: =item * &head()
 5503: 
 5504: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5505: 
 5506: Inputs:
 5507: 
 5508: =over 4
 5509: 
 5510: $title - optional title for the page
 5511: 
 5512: $head_extra - optional extra HTML to put inside the <head>
 5513: 
 5514: =back
 5515: 
 5516: =cut
 5517: 
 5518: sub head {
 5519:     my ($title,$head_extra,$args) = @_;
 5520:     return &headtag($title,$head_extra,$args).&endheadtag();
 5521: }
 5522: 
 5523: =pod
 5524: 
 5525: =item * &start_page()
 5526: 
 5527: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5528: 
 5529: Inputs:
 5530: 
 5531: =over 4
 5532: 
 5533: $title - optional title for the page
 5534: 
 5535: $head_extra - optional extra HTML to incude inside the <head>
 5536: 
 5537: $args - additional optional args supported are:
 5538: 
 5539: =over 8
 5540: 
 5541:              only_body      -> is true will set &bodytag() onlybodytag
 5542:                                     arg on
 5543:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5544:              add_entries    -> additional attributes to add to the  <body>
 5545:              domain         -> force to color decorate a page for a 
 5546:                                     specific domain
 5547:              function       -> force usage of a specific rolish color
 5548:                                     scheme
 5549:              redirect       -> see &headtag()
 5550:              bgcolor        -> override the default page bg color
 5551:              js_ready       -> return a string ready for being used in 
 5552:                                     a javascript writeln
 5553:              html_encode    -> return a string ready for being used in 
 5554:                                     a html attribute
 5555:              force_register -> if is true will turn on the &bodytag()
 5556:                                     $forcereg arg
 5557:              body_title     -> alternate text to use instead of $title
 5558:                                     in the title box that appears, this text
 5559:                                     is not auto translated like the $title is
 5560:              frameset       -> if true will start with a <frameset>
 5561:                                     rather than <body>
 5562:              no_title       -> if true the title bar won't be shown
 5563:              skip_phases    -> hash ref of 
 5564:                                     head -> skip the <html><head> generation
 5565:                                     body -> skip all <body> generation
 5566:              no_inline_link -> if true and in remote mode, don't show the 
 5567:                                     'Switch To Inline Menu' link
 5568:              no_auto_mt_title -> prevent &mt()ing the title arg
 5569:              inherit_jsmath -> when creating popup window in a page,
 5570:                                     should it have jsmath forced on by the
 5571:                                     current page
 5572: 
 5573: =back
 5574: 
 5575: =back
 5576: 
 5577: =cut
 5578: 
 5579: sub start_page {
 5580:     my ($title,$head_extra,$args) = @_;
 5581:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5582:     my %head_args;
 5583:     foreach my $arg ('redirect','force_register','domain','function',
 5584: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5585: 		     'no_auto_mt_title') {
 5586: 	if (defined($args->{$arg})) {
 5587: 	    $head_args{$arg} = $args->{$arg};
 5588: 	}
 5589:     }
 5590: 
 5591:     $env{'internal.start_page'}++;
 5592:     my $result;
 5593:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 5594: 	$result.=
 5595: 	    &xml_begin().
 5596: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 5597:     }
 5598:     
 5599:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 5600: 	if ($args->{'frameset'}) {
 5601: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 5602: 						$args->{'add_entries'});
 5603: 	    $result .= "\n<frameset $attr_string>\n";
 5604: 	} else {
 5605: 	    $result .=
 5606: 		&bodytag($title, 
 5607: 			 $args->{'function'},       $args->{'add_entries'},
 5608: 			 $args->{'only_body'},      $args->{'domain'},
 5609: 			 $args->{'force_register'}, $args->{'body_title'},
 5610: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 5611: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 5612: 			 $args);
 5613: 	}
 5614:     }
 5615: 
 5616:     if ($args->{'js_ready'}) {
 5617: 	$result = &js_ready($result);
 5618:     }
 5619:     if ($args->{'html_encode'}) {
 5620: 	$result = &html_encode($result);
 5621:     }
 5622:     return $result;
 5623: }
 5624: 
 5625: 
 5626: =pod
 5627: 
 5628: =item * &head()
 5629: 
 5630: Returns a complete </body></html> section for LON-CAPA web pages.
 5631: 
 5632: Inputs:         $args - additional optional args supported are:
 5633:                  js_ready     -> return a string ready for being used in 
 5634:                                  a javascript writeln
 5635:                  html_encode  -> return a string ready for being used in 
 5636:                                  a html attribute
 5637:                  frameset     -> if true will start with a <frameset>
 5638:                                  rather than <body>
 5639:                  dicsussion   -> if true will get discussion from
 5640:                                   lonxml::xmlend
 5641:                                  (you can pass the target and parser arguments
 5642:                                   through optional 'target' and 'parser' args
 5643:                                   to this routine)
 5644: 
 5645: =cut
 5646: 
 5647: sub end_page {
 5648:     my ($args) = @_;
 5649:     $env{'internal.end_page'}++;
 5650:     my $result;
 5651:     if ($args->{'discussion'}) {
 5652: 	my ($target,$parser);
 5653: 	if (ref($args->{'discussion'})) {
 5654: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 5655: 				$args->{'discussion'}{'parser'});
 5656: 	}
 5657: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 5658:     }
 5659: 
 5660:     if ($args->{'frameset'}) {
 5661: 	$result .= '</frameset>';
 5662:     } else {
 5663: 	$result .= &endbodytag($args);
 5664:     }
 5665:     $result .= "\n</html>";
 5666: 
 5667:     if ($args->{'js_ready'}) {
 5668: 	$result = &js_ready($result);
 5669:     }
 5670: 
 5671:     if ($args->{'html_encode'}) {
 5672: 	$result = &html_encode($result);
 5673:     }
 5674: 
 5675:     return $result;
 5676: }
 5677: 
 5678: sub html_encode {
 5679:     my ($result) = @_;
 5680: 
 5681:     $result = &HTML::Entities::encode($result,'<>&"');
 5682:     
 5683:     return $result;
 5684: }
 5685: sub js_ready {
 5686:     my ($result) = @_;
 5687: 
 5688:     $result =~ s/[\n\r]/ /xmsg;
 5689:     $result =~ s/\\/\\\\/xmsg;
 5690:     $result =~ s/'/\\'/xmsg;
 5691:     $result =~ s{</}{<\\/}xmsg;
 5692:     
 5693:     return $result;
 5694: }
 5695: 
 5696: sub validate_page {
 5697:     if (  exists($env{'internal.start_page'})
 5698: 	  &&     $env{'internal.start_page'} > 1) {
 5699: 	&Apache::lonnet::logthis('start_page called multiple times '.
 5700: 				 $env{'internal.start_page'}.' '.
 5701: 				 $ENV{'request.filename'});
 5702:     }
 5703:     if (  exists($env{'internal.end_page'})
 5704: 	  &&     $env{'internal.end_page'} > 1) {
 5705: 	&Apache::lonnet::logthis('end_page called multiple times '.
 5706: 				 $env{'internal.end_page'}.' '.
 5707: 				 $env{'request.filename'});
 5708:     }
 5709:     if (     exists($env{'internal.start_page'})
 5710: 	&& ! exists($env{'internal.end_page'})) {
 5711: 	&Apache::lonnet::logthis('start_page called without end_page '.
 5712: 				 $env{'request.filename'});
 5713:     }
 5714:     if (   ! exists($env{'internal.start_page'})
 5715: 	&&   exists($env{'internal.end_page'})) {
 5716: 	&Apache::lonnet::logthis('end_page called without start_page'.
 5717: 				 $env{'request.filename'});
 5718:     }
 5719: }
 5720: 
 5721: sub simple_error_page {
 5722:     my ($r,$title,$msg) = @_;
 5723:     my $page =
 5724: 	&Apache::loncommon::start_page($title).
 5725: 	&mt($msg).
 5726: 	&Apache::loncommon::end_page();
 5727:     if (ref($r)) {
 5728: 	$r->print($page);
 5729: 	return;
 5730:     }
 5731:     return $page;
 5732: }
 5733: 
 5734: {
 5735:     my @row_count;
 5736:     sub start_data_table {
 5737: 	my ($add_class) = @_;
 5738: 	my $css_class = (join(' ','LC_data_table',$add_class));
 5739: 	unshift(@row_count,0);
 5740: 	return '<table class="'.$css_class.'">'."\n";
 5741:     }
 5742: 
 5743:     sub end_data_table {
 5744: 	shift(@row_count);
 5745: 	return '</table>'."\n";;
 5746:     }
 5747: 
 5748:     sub start_data_table_row {
 5749: 	my ($add_class) = @_;
 5750: 	$row_count[0]++;
 5751: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5752: 	$css_class = (join(' ',$css_class,$add_class));
 5753: 	return  '<tr class="'.$css_class.'">'."\n";;
 5754:     }
 5755:     
 5756:     sub continue_data_table_row {
 5757: 	my ($add_class) = @_;
 5758: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5759: 	$css_class = (join(' ',$css_class,$add_class));
 5760: 	return  '<tr class="'.$css_class.'">'."\n";;
 5761:     }
 5762: 
 5763:     sub end_data_table_row {
 5764: 	return '</tr>'."\n";;
 5765:     }
 5766: 
 5767:     sub start_data_table_empty_row {
 5768: 	$row_count[0]++;
 5769: 	return  '<tr class="LC_empty_row" >'."\n";;
 5770:     }
 5771: 
 5772:     sub end_data_table_empty_row {
 5773: 	return '</tr>'."\n";;
 5774:     }
 5775: 
 5776:     sub start_data_table_header_row {
 5777: 	return  '<tr class="LC_header_row">'."\n";;
 5778:     }
 5779: 
 5780:     sub end_data_table_header_row {
 5781: 	return '</tr>'."\n";;
 5782:     }
 5783: }
 5784: 
 5785: =pod
 5786: 
 5787: =item * &inhibit_menu_check($arg)
 5788: 
 5789: Checks for a inhibitmenu state and generates output to preserve it
 5790: 
 5791: Inputs:         $arg - can be any of
 5792:                      - undef - in which case the return value is a string 
 5793:                                to add  into arguments list of a uri
 5794:                      - 'input' - in which case the return value is a HTML
 5795:                                  <form> <input> field of type hidden to
 5796:                                  preserve the value
 5797:                      - a url - in which case the return value is the url with
 5798:                                the neccesary cgi args added to preserve the
 5799:                                inhibitmenu state
 5800:                      - a ref to a url - no return value, but the string is
 5801:                                         updated to include the neccessary cgi
 5802:                                         args to preserve the inhibitmenu state
 5803: 
 5804: =cut
 5805: 
 5806: sub inhibit_menu_check {
 5807:     my ($arg) = @_;
 5808:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5809:     if ($arg eq 'input') {
 5810: 	if ($env{'form.inhibitmenu'}) {
 5811: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 5812: 	} else {
 5813: 	    return
 5814: 	}
 5815:     }
 5816:     if ($env{'form.inhibitmenu'}) {
 5817: 	if (ref($arg)) {
 5818: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5819: 	} elsif ($arg eq '') {
 5820: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 5821: 	} else {
 5822: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5823: 	}
 5824:     }
 5825:     if (!ref($arg)) {
 5826: 	return $arg;
 5827:     }
 5828: }
 5829: 
 5830: ###############################################
 5831: 
 5832: =pod
 5833: 
 5834: =back
 5835: 
 5836: =head1 User Information Routines
 5837: 
 5838: =over 4
 5839: 
 5840: =item * &get_users_function()
 5841: 
 5842: Used by &bodytag to determine the current users primary role.
 5843: Returns either 'student','coordinator','admin', or 'author'.
 5844: 
 5845: =cut
 5846: 
 5847: ###############################################
 5848: sub get_users_function {
 5849:     my $function = 'student';
 5850:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 5851:         $function='coordinator';
 5852:     }
 5853:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 5854:         $function='admin';
 5855:     }
 5856:     if (($env{'request.role'}=~/^(au|ca)/) ||
 5857:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 5858:         $function='author';
 5859:     }
 5860:     return $function;
 5861: }
 5862: 
 5863: ###############################################
 5864: 
 5865: =pod
 5866: 
 5867: =item * &check_user_status()
 5868: 
 5869: Determines current status of supplied role for a
 5870: specific user. Roles can be active, previous or future.
 5871: 
 5872: Inputs: 
 5873: user's domain, user's username, course's domain,
 5874: course's number, optional section ID.
 5875: 
 5876: Outputs:
 5877: role status: active, previous or future. 
 5878: 
 5879: =cut
 5880: 
 5881: sub check_user_status {
 5882:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 5883:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 5884:     my @uroles = keys %userinfo;
 5885:     my $srchstr;
 5886:     my $active_chk = 'none';
 5887:     my $now = time;
 5888:     if (@uroles > 0) {
 5889:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 5890:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 5891:         } else {
 5892:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 5893:         }
 5894:         if (grep/^\Q$srchstr\E$/,@uroles) {
 5895:             my $role_end = 0;
 5896:             my $role_start = 0;
 5897:             $active_chk = 'active';
 5898:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 5899:                 $role_end = $1;
 5900:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 5901:                     $role_start = $1;
 5902:                 }
 5903:             }
 5904:             if ($role_start > 0) {
 5905:                 if ($now < $role_start) {
 5906:                     $active_chk = 'future';
 5907:                 }
 5908:             }
 5909:             if ($role_end > 0) {
 5910:                 if ($now > $role_end) {
 5911:                     $active_chk = 'previous';
 5912:                 }
 5913:             }
 5914:         }
 5915:     }
 5916:     return $active_chk;
 5917: }
 5918: 
 5919: ###############################################
 5920: 
 5921: =pod
 5922: 
 5923: =item * &get_sections()
 5924: 
 5925: Determines all the sections for a course including
 5926: sections with students and sections containing other roles.
 5927: Incoming parameters: 
 5928: 
 5929: 1. domain
 5930: 2. course number 
 5931: 3. reference to array containing roles for which sections should 
 5932: be gathered (optional).
 5933: 4. reference to array containing status types for which sections 
 5934: should be gathered (optional).
 5935: 
 5936: If the third argument is undefined, sections are gathered for any role. 
 5937: If the fourth argument is undefined, sections are gathered for any status.
 5938: Permissible values are 'active' or 'future' or 'previous'.
 5939:  
 5940: Returns section hash (keys are section IDs, values are
 5941: number of users in each section), subject to the
 5942: optional roles filter, optional status filter 
 5943: 
 5944: =cut
 5945: 
 5946: ###############################################
 5947: sub get_sections {
 5948:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 5949:     if (!defined($cdom) || !defined($cnum)) {
 5950:         my $cid =  $env{'request.course.id'};
 5951: 
 5952: 	return if (!defined($cid));
 5953: 
 5954:         $cdom = $env{'course.'.$cid.'.domain'};
 5955:         $cnum = $env{'course.'.$cid.'.num'};
 5956:     }
 5957: 
 5958:     my %sectioncount;
 5959:     my $now = time;
 5960: 
 5961:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 5962: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 5963: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 5964: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 5965:         my $start_index = &Apache::loncoursedata::CL_START();
 5966:         my $end_index = &Apache::loncoursedata::CL_END();
 5967:         my $status;
 5968: 	while (my ($student,$data) = each(%$classlist)) {
 5969: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 5970: 				                     $data->[$status_index],
 5971:                                                      $data->[$start_index],
 5972:                                                      $data->[$end_index]);
 5973:             if ($stu_status eq 'Active') {
 5974:                 $status = 'active';
 5975:             } elsif ($end < $now) {
 5976:                 $status = 'previous';
 5977:             } elsif ($start > $now) {
 5978:                 $status = 'future';
 5979:             } 
 5980: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 5981:                 if ((!defined($possible_status)) || (($status ne '') && 
 5982:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 5983: 		    $sectioncount{$section}++;
 5984:                 }
 5985: 	    }
 5986: 	}
 5987:     }
 5988:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 5989:     foreach my $user (sort(keys(%courseroles))) {
 5990: 	if ($user !~ /^(\w{2})/) { next; }
 5991: 	my ($role) = ($user =~ /^(\w{2})/);
 5992: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 5993: 	my ($section,$status);
 5994: 	if ($role eq 'cr' &&
 5995: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 5996: 	    $section=$1;
 5997: 	}
 5998: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 5999: 	if (!defined($section) || $section eq '-1') { next; }
 6000:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6001:         if ($end == -1 && $start == -1) {
 6002:             next; #deleted role
 6003:         }
 6004:         if (!defined($possible_status)) { 
 6005:             $sectioncount{$section}++;
 6006:         } else {
 6007:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6008:                 $status = 'active';
 6009:             } elsif ($end < $now) {
 6010:                 $status = 'future';
 6011:             } elsif ($start > $now) {
 6012:                 $status = 'previous';
 6013:             }
 6014:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6015:                 $sectioncount{$section}++;
 6016:             }
 6017:         }
 6018:     }
 6019:     return %sectioncount;
 6020: }
 6021: 
 6022: ###############################################
 6023: 
 6024: =pod
 6025: 
 6026: =item * &get_course_users()
 6027: 
 6028: Retrieves usernames:domains for users in the specified course
 6029: with specific role(s), and access status. 
 6030: 
 6031: Incoming parameters:
 6032: 1. course domain
 6033: 2. course number
 6034: 3. access status: users must have - either active, 
 6035: previous, future, or all.
 6036: 4. reference to array of permissible roles
 6037: 5. reference to array of section restrictions (optional)
 6038: 6. reference to results object (hash of hashes).
 6039: 7. reference to optional userdata hash
 6040: 8. reference to optional statushash
 6041: 9. flag if privileged users (except those set to unhide in
 6042:    course settings) should be excluded    
 6043: Keys of top level results hash are roles.
 6044: Keys of inner hashes are username:domain, with 
 6045: values set to access type.
 6046: Optional userdata hash returns an array with arguments in the 
 6047: same order as loncoursedata::get_classlist() for student data.
 6048: 
 6049: Optional statushash returns
 6050: 
 6051: Entries for end, start, section and status are blank because
 6052: of the possibility of multiple values for non-student roles.
 6053: 
 6054: =cut
 6055: 
 6056: ###############################################
 6057: 
 6058: sub get_course_users {
 6059:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6060:     my %idx = ();
 6061:     my %seclists;
 6062: 
 6063:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6064:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6065:     $idx{end} = &Apache::loncoursedata::CL_END();
 6066:     $idx{start} = &Apache::loncoursedata::CL_START();
 6067:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6068:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6069:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6070:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6071: 
 6072:     if (grep(/^st$/,@{$roles})) {
 6073:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6074:         my $now = time;
 6075:         foreach my $student (keys(%{$classlist})) {
 6076:             my $match = 0;
 6077:             my $secmatch = 0;
 6078:             my $section = $$classlist{$student}[$idx{section}];
 6079:             my $status = $$classlist{$student}[$idx{status}];
 6080:             if ($section eq '') {
 6081:                 $section = 'none';
 6082:             }
 6083:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6084:                 if (grep(/^all$/,@{$sections})) {
 6085:                     $secmatch = 1;
 6086:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6087:                     if (grep(/^none$/,@{$sections})) {
 6088:                         $secmatch = 1;
 6089:                     }
 6090:                 } else {  
 6091: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6092: 		        $secmatch = 1;
 6093:                     }
 6094: 		}
 6095:                 if (!$secmatch) {
 6096:                     next;
 6097:                 }
 6098:             }
 6099:             if (defined($$types{'active'})) {
 6100:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6101:                     push(@{$$users{st}{$student}},'active');
 6102:                     $match = 1;
 6103:                 }
 6104:             }
 6105:             if (defined($$types{'previous'})) {
 6106:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6107:                     push(@{$$users{st}{$student}},'previous');
 6108:                     $match = 1;
 6109:                 }
 6110:             }
 6111:             if (defined($$types{'future'})) {
 6112:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6113:                     push(@{$$users{st}{$student}},'future');
 6114:                     $match = 1;
 6115:                 }
 6116:             }
 6117:             if ($match) {
 6118:                 push(@{$seclists{$student}},$section);
 6119:                 if (ref($userdata) eq 'HASH') {
 6120:                     $$userdata{$student} = $$classlist{$student};
 6121:                 }
 6122:                 if (ref($statushash) eq 'HASH') {
 6123:                     $statushash->{$student}{'st'}{$section} = $status;
 6124:                 }
 6125:             }
 6126:         }
 6127:     }
 6128:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6129:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6130:         my $now = time;
 6131:         my %displaystatus = ( previous => 'Expired',
 6132:                               active   => 'Active',
 6133:                               future   => 'Future',
 6134:                             );
 6135:         my %nothide;
 6136:         if ($hidepriv) {
 6137:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6138:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6139:                 if ($user !~ /:/) {
 6140:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6141:                 } else {
 6142:                     $nothide{$user} = 1;
 6143:                 }
 6144:             }
 6145:         }
 6146:         foreach my $person (sort(keys(%coursepersonnel))) {
 6147:             my $match = 0;
 6148:             my $secmatch = 0;
 6149:             my $status;
 6150:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6151:             $user =~ s/:$//;
 6152:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6153:             if ($end == -1 || $start == -1) {
 6154:                 next;
 6155:             }
 6156:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6157:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6158:                 my ($uname,$udom) = split(/:/,$user);
 6159:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6160:                     if (grep(/^all$/,@{$sections})) {
 6161:                         $secmatch = 1;
 6162:                     } elsif ($usec eq '') {
 6163:                         if (grep(/^none$/,@{$sections})) {
 6164:                             $secmatch = 1;
 6165:                         }
 6166:                     } else {
 6167:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6168:                             $secmatch = 1;
 6169:                         }
 6170:                     }
 6171:                     if (!$secmatch) {
 6172:                         next;
 6173:                     }
 6174:                 }
 6175:                 if ($usec eq '') {
 6176:                     $usec = 'none';
 6177:                 }
 6178:                 if ($uname ne '' && $udom ne '') {
 6179:                     if ($hidepriv) {
 6180:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6181:                             (!$nothide{$uname.':'.$udom})) {
 6182:                             next;
 6183:                         }
 6184:                     }
 6185:                     if ($end > 0 && $end < $now) {
 6186:                         $status = 'previous';
 6187:                     } elsif ($start > $now) {
 6188:                         $status = 'future';
 6189:                     } else {
 6190:                         $status = 'active';
 6191:                     }
 6192:                     foreach my $type (keys(%{$types})) { 
 6193:                         if ($status eq $type) {
 6194:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6195:                                 push(@{$$users{$role}{$user}},$type);
 6196:                             }
 6197:                             $match = 1;
 6198:                         }
 6199:                     }
 6200:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6201:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6202: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6203:                         }
 6204:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6205:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6206:                         }
 6207:                         if (ref($statushash) eq 'HASH') {
 6208:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6209:                         }
 6210:                     }
 6211:                 }
 6212:             }
 6213:         }
 6214:         if (grep(/^ow$/,@{$roles})) {
 6215:             if ((defined($cdom)) && (defined($cnum))) {
 6216:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6217:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6218:                     my $owner = $csettings{'internal.courseowner'};
 6219:                     next if ($owner eq '');
 6220:                     my ($ownername,$ownerdom);
 6221:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6222:                         $ownername = $1;
 6223:                         $ownerdom = $2;
 6224:                     } else {
 6225:                         $ownername = $owner;
 6226:                         $ownerdom = $cdom;
 6227:                         $owner = $ownername.':'.$ownerdom;
 6228:                     }
 6229:                     @{$$users{'ow'}{$owner}} = 'any';
 6230:                     if (defined($userdata) && 
 6231: 			!exists($$userdata{$owner})) {
 6232: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6233:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6234:                             push(@{$seclists{$owner}},'none');
 6235:                         }
 6236:                         if (ref($statushash) eq 'HASH') {
 6237:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6238:                         }
 6239: 		    }
 6240:                 }
 6241:             }
 6242:         }
 6243:         foreach my $user (keys(%seclists)) {
 6244:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6245:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6246:         }
 6247:     }
 6248:     return;
 6249: }
 6250: 
 6251: sub get_user_info {
 6252:     my ($udom,$uname,$idx,$userdata) = @_;
 6253:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6254: 	&plainname($uname,$udom,'lastname');
 6255:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6256:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6257:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6258:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6259:     return;
 6260: }
 6261: 
 6262: ###############################################
 6263: 
 6264: =pod
 6265: 
 6266: =item * &get_user_quota()
 6267: 
 6268: Retrieves quota assigned for storage of portfolio files for a user  
 6269: 
 6270: Incoming parameters:
 6271: 1. user's username
 6272: 2. user's domain
 6273: 
 6274: Returns:
 6275: 1. Disk quota (in Mb) assigned to student.
 6276: 2. (Optional) Type of setting: custom or default
 6277:    (individually assigned or default for user's 
 6278:    institutional status).
 6279: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6280:    or student - types as defined in localenroll::inst_usertypes 
 6281:    for user's domain, which determines default quota for user.
 6282: 4. (Optional) - Default quota which would apply to the user.
 6283: 
 6284: If a value has been stored in the user's environment, 
 6285: it will return that, otherwise it returns the maximal default
 6286: defined for the user's instituional status(es) in the domain.
 6287: 
 6288: =cut
 6289: 
 6290: ###############################################
 6291: 
 6292: 
 6293: sub get_user_quota {
 6294:     my ($uname,$udom) = @_;
 6295:     my ($quota,$quotatype,$settingstatus,$defquota);
 6296:     if (!defined($udom)) {
 6297:         $udom = $env{'user.domain'};
 6298:     }
 6299:     if (!defined($uname)) {
 6300:         $uname = $env{'user.name'};
 6301:     }
 6302:     if (($udom eq '' || $uname eq '') ||
 6303:         ($udom eq 'public') && ($uname eq 'public')) {
 6304:         $quota = 0;
 6305:         $quotatype = 'default';
 6306:         $defquota = 0; 
 6307:     } else {
 6308:         my $inststatus;
 6309:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6310:             $quota = $env{'environment.portfolioquota'};
 6311:             $inststatus = $env{'environment.inststatus'};
 6312:         } else {
 6313:             my %userenv = 
 6314:                 &Apache::lonnet::get('environment',['portfolioquota',
 6315:                                      'inststatus'],$udom,$uname);
 6316:             my ($tmp) = keys(%userenv);
 6317:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6318:                 $quota = $userenv{'portfolioquota'};
 6319:                 $inststatus = $userenv{'inststatus'};
 6320:             } else {
 6321:                 undef(%userenv);
 6322:             }
 6323:         }
 6324:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6325:         if ($quota eq '') {
 6326:             $quota = $defquota;
 6327:             $quotatype = 'default';
 6328:         } else {
 6329:             $quotatype = 'custom';
 6330:         }
 6331:     }
 6332:     if (wantarray) {
 6333:         return ($quota,$quotatype,$settingstatus,$defquota);
 6334:     } else {
 6335:         return $quota;
 6336:     }
 6337: }
 6338: 
 6339: ###############################################
 6340: 
 6341: =pod
 6342: 
 6343: =item * &default_quota()
 6344: 
 6345: Retrieves default quota assigned for storage of user portfolio files,
 6346: given an (optional) user's institutional status.
 6347: 
 6348: Incoming parameters:
 6349: 1. domain
 6350: 2. (Optional) institutional status(es).  This is a : separated list of 
 6351:    status types (e.g., faculty, staff, student etc.)
 6352:    which apply to the user for whom the default is being retrieved.
 6353:    If the institutional status string in undefined, the domain
 6354:    default quota will be returned. 
 6355: 
 6356: Returns:
 6357: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6358: 2. (Optional) institutional type which determined the value of the
 6359:    default quota.
 6360: 
 6361: If a value has been stored in the domain's configuration db,
 6362: it will return that, otherwise it returns 20 (for backwards 
 6363: compatibility with domains which have not set up a configuration
 6364: db file; the original statically defined portfolio quota was 20 Mb). 
 6365: 
 6366: If the user's status includes multiple types (e.g., staff and student),
 6367: the largest default quota which applies to the user determines the
 6368: default quota returned.
 6369: 
 6370: =cut
 6371: 
 6372: ###############################################
 6373: 
 6374: 
 6375: sub default_quota {
 6376:     my ($udom,$inststatus) = @_;
 6377:     my ($defquota,$settingstatus);
 6378:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6379:                                             ['quotas'],$udom);
 6380:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6381:         if ($inststatus ne '') {
 6382:             my @statuses = split(/:/,$inststatus);
 6383:             foreach my $item (@statuses) {
 6384:                 if ($quotahash{'quotas'}{$item} ne '') {
 6385:                     if ($defquota eq '') {
 6386:                         $defquota = $quotahash{'quotas'}{$item};
 6387:                         $settingstatus = $item;
 6388:                     } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6389:                         $defquota = $quotahash{'quotas'}{$item};
 6390:                         $settingstatus = $item;
 6391:                     }
 6392:                 }
 6393:             }
 6394:         }
 6395:         if ($defquota eq '') {
 6396:             $defquota = $quotahash{'quotas'}{'default'};
 6397:             $settingstatus = 'default';
 6398:         }
 6399:     } else {
 6400:         $settingstatus = 'default';
 6401:         $defquota = 20;
 6402:     }
 6403:     if (wantarray) {
 6404:         return ($defquota,$settingstatus);
 6405:     } else {
 6406:         return $defquota;
 6407:     }
 6408: }
 6409: 
 6410: sub get_secgrprole_info {
 6411:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6412:     my %sections_count = &get_sections($cdom,$cnum);
 6413:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6414:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6415:     my @groups = sort(keys(%curr_groups));
 6416:     my $allroles = [];
 6417:     my $rolehash;
 6418:     my $accesshash = {
 6419:                      active => 'Currently has access',
 6420:                      future => 'Will have future access',
 6421:                      previous => 'Previously had access',
 6422:                   };
 6423:     if ($needroles) {
 6424:         $rolehash = {'all' => 'all'};
 6425:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6426: 	if (&Apache::lonnet::error(%user_roles)) {
 6427: 	    undef(%user_roles);
 6428: 	}
 6429:         foreach my $item (keys(%user_roles)) {
 6430:             my ($role)=split(/\:/,$item,2);
 6431:             if ($role eq 'cr') { next; }
 6432:             if ($role =~ /^cr/) {
 6433:                 $$rolehash{$role} = (split('/',$role))[3];
 6434:             } else {
 6435:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6436:             }
 6437:         }
 6438:         foreach my $key (sort(keys(%{$rolehash}))) {
 6439:             push(@{$allroles},$key);
 6440:         }
 6441:         push (@{$allroles},'st');
 6442:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6443:     }
 6444:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6445: }
 6446: 
 6447: sub user_picker {
 6448:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6449:     my $currdom = $dom;
 6450:     my %curr_selected = (
 6451:                         srchin => 'dom',
 6452:                         srchby => 'lastname',
 6453:                       );
 6454:     my $srchterm;
 6455:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6456:         if ($srch->{'srchby'} ne '') {
 6457:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6458:         }
 6459:         if ($srch->{'srchin'} ne '') {
 6460:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6461:         }
 6462:         if ($srch->{'srchtype'} ne '') {
 6463:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6464:         }
 6465:         if ($srch->{'srchdomain'} ne '') {
 6466:             $currdom = $srch->{'srchdomain'};
 6467:         }
 6468:         $srchterm = $srch->{'srchterm'};
 6469:     }
 6470:     my %lt=&Apache::lonlocal::texthash(
 6471:                     'usr'       => 'Search criteria',
 6472:                     'doma'      => 'Domain/institution to search',
 6473:                     'uname'     => 'username',
 6474:                     'lastname'  => 'last name',
 6475:                     'lastfirst' => 'last name, first name',
 6476:                     'crs'       => 'in this course',
 6477:                     'dom'       => 'in selected LON-CAPA domain', 
 6478:                     'alc'       => 'all LON-CAPA',
 6479:                     'instd'     => 'in institutional directory for selected domain',
 6480:                     'exact'     => 'is',
 6481:                     'contains'  => 'contains',
 6482:                     'begins'    => 'begins with',
 6483:                     'youm'      => "You must include some text to search for.",
 6484:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6485:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6486:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6487:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6488:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6489:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6490:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6491:                                        );
 6492:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6493:     my $srchinsel = ' <select name="srchin">';
 6494: 
 6495:     my @srchins = ('crs','dom','alc','instd');
 6496: 
 6497:     foreach my $option (@srchins) {
 6498:         # FIXME 'alc' option unavailable until 
 6499:         #       loncreateuser::print_user_query_page()
 6500:         #       has been completed.
 6501:         next if ($option eq 'alc');
 6502:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6503:         if ($curr_selected{'srchin'} eq $option) {
 6504:             $srchinsel .= ' 
 6505:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6506:         } else {
 6507:             $srchinsel .= '
 6508:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6509:         }
 6510:     }
 6511:     $srchinsel .= "\n  </select>\n";
 6512: 
 6513:     my $srchbysel =  ' <select name="srchby">';
 6514:     foreach my $option ('lastname','lastfirst','uname') {
 6515:         if ($curr_selected{'srchby'} eq $option) {
 6516:             $srchbysel .= '
 6517:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6518:         } else {
 6519:             $srchbysel .= '
 6520:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6521:          }
 6522:     }
 6523:     $srchbysel .= "\n  </select>\n";
 6524: 
 6525:     my $srchtypesel = ' <select name="srchtype">';
 6526:     foreach my $option ('begins','contains','exact') {
 6527:         if ($curr_selected{'srchtype'} eq $option) {
 6528:             $srchtypesel .= '
 6529:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6530:         } else {
 6531:             $srchtypesel .= '
 6532:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6533:         }
 6534:     }
 6535:     $srchtypesel .= "\n  </select>\n";
 6536: 
 6537:     my ($newuserscript,$new_user_create);
 6538: 
 6539:     if ($forcenewuser) {
 6540:         if (ref($srch) eq 'HASH') {
 6541:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 6542:                 if ($cancreate) {
 6543:                     $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>';
 6544:                 } else {
 6545:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6546:                     my %usertypetext = (
 6547:                         official   => 'institutional',
 6548:                         unofficial => 'non-institutional',
 6549:                     );
 6550:                     $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 />';
 6551:                 }
 6552:             }
 6553:         }
 6554: 
 6555:         $newuserscript = <<"ENDSCRIPT";
 6556: 
 6557: function setSearch(createnew,callingForm) {
 6558:     if (createnew == 1) {
 6559:         for (var i=0; i<callingForm.srchby.length; i++) {
 6560:             if (callingForm.srchby.options[i].value == 'uname') {
 6561:                 callingForm.srchby.selectedIndex = i;
 6562:             }
 6563:         }
 6564:         for (var i=0; i<callingForm.srchin.length; i++) {
 6565:             if ( callingForm.srchin.options[i].value == 'dom') {
 6566: 		callingForm.srchin.selectedIndex = i;
 6567:             }
 6568:         }
 6569:         for (var i=0; i<callingForm.srchtype.length; i++) {
 6570:             if (callingForm.srchtype.options[i].value == 'exact') {
 6571:                 callingForm.srchtype.selectedIndex = i;
 6572:             }
 6573:         }
 6574:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 6575:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 6576:                 callingForm.srchdomain.selectedIndex = i;
 6577:             }
 6578:         }
 6579:     }
 6580: }
 6581: ENDSCRIPT
 6582: 
 6583:     }
 6584: 
 6585:     my $output = <<"END_BLOCK";
 6586: <script type="text/javascript">
 6587: function validateEntry(callingForm) {
 6588: 
 6589:     var checkok = 1;
 6590:     var srchin;
 6591:     for (var i=0; i<callingForm.srchin.length; i++) {
 6592: 	if ( callingForm.srchin[i].checked ) {
 6593: 	    srchin = callingForm.srchin[i].value;
 6594: 	}
 6595:     }
 6596: 
 6597:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 6598:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 6599:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 6600:     var srchterm =  callingForm.srchterm.value;
 6601:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 6602:     var msg = "";
 6603: 
 6604:     if (srchterm == "") {
 6605:         checkok = 0;
 6606:         msg += "$lt{'youm'}\\n";
 6607:     }
 6608: 
 6609:     if (srchtype== 'begins') {
 6610:         if (srchterm.length < 2) {
 6611:             checkok = 0;
 6612:             msg += "$lt{'thte'}\\n";
 6613:         }
 6614:     }
 6615: 
 6616:     if (srchtype== 'contains') {
 6617:         if (srchterm.length < 3) {
 6618:             checkok = 0;
 6619:             msg += "$lt{'thet'}\\n";
 6620:         }
 6621:     }
 6622:     if (srchin == 'instd') {
 6623:         if (srchdomain == '') {
 6624:             checkok = 0;
 6625:             msg += "$lt{'yomc'}\\n";
 6626:         }
 6627:     }
 6628:     if (srchin == 'dom') {
 6629:         if (srchdomain == '') {
 6630:             checkok = 0;
 6631:             msg += "$lt{'ymcd'}\\n";
 6632:         }
 6633:     }
 6634:     if (srchby == 'lastfirst') {
 6635:         if (srchterm.indexOf(",") == -1) {
 6636:             checkok = 0;
 6637:             msg += "$lt{'whus'}\\n";
 6638:         }
 6639:         if (srchterm.indexOf(",") == srchterm.length -1) {
 6640:             checkok = 0;
 6641:             msg += "$lt{'whse'}\\n";
 6642:         }
 6643:     }
 6644:     if (checkok == 0) {
 6645:         alert("$lt{'thfo'}\\n"+msg);
 6646:         return;
 6647:     }
 6648:     if (checkok == 1) {
 6649:         callingForm.submit();
 6650:     }
 6651: }
 6652: 
 6653: $newuserscript
 6654: 
 6655: </script>
 6656: 
 6657: $new_user_create
 6658: 
 6659: <table>
 6660:  <tr>
 6661:   <td>$lt{'doma'}:</td>
 6662:   <td>$domform</td>
 6663:   </td>
 6664:  </tr>
 6665:  <tr>
 6666:   <td>$lt{'usr'}:</td>
 6667:   <td>$srchbysel
 6668:       $srchtypesel 
 6669:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 6670:       $srchinsel 
 6671:   </td>
 6672:  </tr>
 6673: </table>
 6674: <br />
 6675: END_BLOCK
 6676: 
 6677:     return $output;
 6678: }
 6679: 
 6680: sub user_rule_check {
 6681:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 6682:     my $response;
 6683:     if (ref($usershash) eq 'HASH') {
 6684:         foreach my $user (keys(%{$usershash})) {
 6685:             my ($uname,$udom) = split(/:/,$user);
 6686:             next if ($udom eq '' || $uname eq '');
 6687:             my ($id,$newuser);
 6688:             if (ref($usershash->{$user}) eq 'HASH') {
 6689:                 $newuser = $usershash->{$user}->{'newuser'};
 6690:                 $id = $usershash->{$user}->{'id'};
 6691:             }
 6692:             my $inst_response;
 6693:             if (ref($checks) eq 'HASH') {
 6694:                 if (defined($checks->{'username'})) {
 6695:                     ($inst_response,%{$inst_results->{$user}}) = 
 6696:                         &Apache::lonnet::get_instuser($udom,$uname);
 6697:                 } elsif (defined($checks->{'id'})) {
 6698:                     ($inst_response,%{$inst_results->{$user}}) =
 6699:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 6700:                 }
 6701:             } else {
 6702:                 ($inst_response,%{$inst_results->{$user}}) =
 6703:                     &Apache::lonnet::get_instuser($udom,$uname);
 6704:                 return;
 6705:             }
 6706:             if (!$got_rules->{$udom}) {
 6707:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 6708:                                                   ['usercreation'],$udom);
 6709:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6710:                     foreach my $item ('username','id') {
 6711:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 6712:                             $$curr_rules{$udom}{$item} = 
 6713:                                 $domconfig{'usercreation'}{$item.'_rule'};
 6714:                         }
 6715:                     }
 6716:                 }
 6717:                 $got_rules->{$udom} = 1;  
 6718:             }
 6719:             foreach my $item (keys(%{$checks})) {
 6720:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 6721:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 6722:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 6723:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 6724:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 6725:                                 if ($rule_check{$rule}) {
 6726:                                     $$rulematch{$user}{$item} = $rule;
 6727:                                     if ($inst_response eq 'ok') {
 6728:                                         if (ref($inst_results) eq 'HASH') {
 6729:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 6730:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 6731:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 6732:                                                 }
 6733:                                             }
 6734:                                         }
 6735:                                     }
 6736:                                     last;
 6737:                                 }
 6738:                             }
 6739:                         }
 6740:                     }
 6741:                 }
 6742:             }
 6743:         }
 6744:     }
 6745:     return;
 6746: }
 6747: 
 6748: sub user_rule_formats {
 6749:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 6750:     my %text = ( 
 6751:                  'username' => 'Usernames',
 6752:                  'id'       => 'IDs',
 6753:                );
 6754:     my $output;
 6755:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 6756:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 6757:         if (@{$ruleorder} > 0) {
 6758:             $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>';
 6759:             foreach my $rule (@{$ruleorder}) {
 6760:                 if (ref($curr_rules) eq 'ARRAY') {
 6761:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 6762:                         if (ref($rules->{$rule}) eq 'HASH') {
 6763:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 6764:                                         $rules->{$rule}{'desc'}.'</li>';
 6765:                         }
 6766:                     }
 6767:                 }
 6768:             }
 6769:             $output .= '</ul>';
 6770:         }
 6771:     }
 6772:     return $output;
 6773: }
 6774: 
 6775: sub instrule_disallow_msg {
 6776:     my ($checkitem,$domdesc,$count,$mode) = @_;
 6777:     my $response;
 6778:     my %text = (
 6779:                   item   => 'username',
 6780:                   items  => 'usernames',
 6781:                   match  => 'matches',
 6782:                   do     => 'does',
 6783:                   action => 'a username',
 6784:                   one    => 'one',
 6785:                );
 6786:     if ($count > 1) {
 6787:         $text{'item'} = 'usernames';
 6788:         $text{'match'} ='match';
 6789:         $text{'do'} = 'do';
 6790:         $text{'action'} = 'usernames',
 6791:         $text{'one'} = 'ones';
 6792:     }
 6793:     if ($checkitem eq 'id') {
 6794:         $text{'items'} = 'IDs';
 6795:         $text{'item'} = 'ID';
 6796:         $text{'action'} = 'an ID';
 6797:         if ($count > 1) {
 6798:             $text{'item'} = 'IDs';
 6799:             $text{'action'} = 'IDs';
 6800:         }
 6801:     }
 6802:     $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 />';
 6803:     if ($mode eq 'upload') {
 6804:         if ($checkitem eq 'username') {
 6805:             $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'}.");
 6806:         } elsif ($checkitem eq 'id') {
 6807:             $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.");
 6808:         }
 6809:     } else {
 6810:         if ($checkitem eq 'username') {
 6811:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 6812:         } elsif ($checkitem eq 'id') {
 6813:             $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.");
 6814:         }
 6815:     }
 6816:     return $response;
 6817: }
 6818: 
 6819: sub personal_data_fieldtitles {
 6820:     my %fieldtitles = &Apache::lonlocal::texthash (
 6821:                         id => 'Student/Employee ID',
 6822:                         permanentemail => 'E-mail address',
 6823:                         lastname => 'Last Name',
 6824:                         firstname => 'First Name',
 6825:                         middlename => 'Middle Name',
 6826:                         generation => 'Generation',
 6827:                         gen => 'Generation',
 6828:                    );
 6829:     return %fieldtitles;
 6830: }
 6831: 
 6832: sub sorted_inst_types {
 6833:     my ($dom) = @_;
 6834:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 6835:     my $othertitle = &mt('All users');
 6836:     if ($env{'request.course.id'}) {
 6837:         $othertitle  = 'any';
 6838:     }
 6839:     my @types;
 6840:     if (ref($order) eq 'ARRAY') {
 6841:         @types = @{$order};
 6842:     }
 6843:     if (@types == 0) {
 6844:         if (ref($usertypes) eq 'HASH') {
 6845:             @types = sort(keys(%{$usertypes}));
 6846:         }
 6847:     }
 6848:     if (keys(%{$usertypes}) > 0) {
 6849:         $othertitle = &mt('Other users');
 6850:         if ($env{'request.course.id'}) {
 6851:             $othertitle = 'other';
 6852:         }
 6853:     }
 6854:     return ($othertitle,$usertypes,\@types);
 6855: }
 6856: 
 6857: sub get_institutional_codes {
 6858:     my ($settings,$allcourses,$LC_code) = @_;
 6859: # Get complete list of course sections to update
 6860:     my @currsections = ();
 6861:     my @currxlists = ();
 6862:     my $coursecode = $$settings{'internal.coursecode'};
 6863: 
 6864:     if ($$settings{'internal.sectionnums'} ne '') {
 6865:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 6866:     }
 6867: 
 6868:     if ($$settings{'internal.crosslistings'} ne '') {
 6869:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 6870:     }
 6871: 
 6872:     if (@currxlists > 0) {
 6873:         foreach (@currxlists) {
 6874:             if (m/^([^:]+):(\w*)$/) {
 6875:                 unless (grep/^$1$/,@{$allcourses}) {
 6876:                     push @{$allcourses},$1;
 6877:                     $$LC_code{$1} = $2;
 6878:                 }
 6879:             }
 6880:         }
 6881:     }
 6882:  
 6883:     if (@currsections > 0) {
 6884:         foreach (@currsections) {
 6885:             if (m/^(\w+):(\w*)$/) {
 6886:                 my $sec = $coursecode.$1;
 6887:                 my $lc_sec = $2;
 6888:                 unless (grep/^$sec$/,@{$allcourses}) {
 6889:                     push @{$allcourses},$sec;
 6890:                     $$LC_code{$sec} = $lc_sec;
 6891:                 }
 6892:             }
 6893:         }
 6894:     }
 6895:     return;
 6896: }
 6897: 
 6898: =pod
 6899: 
 6900: =back
 6901: 
 6902: =head1 HTTP Helpers
 6903: 
 6904: =over 4
 6905: 
 6906: =item * &get_unprocessed_cgi($query,$possible_names)
 6907: 
 6908: Modify the %env hash to contain unprocessed CGI form parameters held in
 6909: $query.  The parameters listed in $possible_names (an array reference),
 6910: will be set in $env{'form.name'} if they do not already exist.
 6911: 
 6912: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 6913: $possible_names is an ref to an array of form element names.  As an example:
 6914: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 6915: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 6916: 
 6917: =cut
 6918: 
 6919: sub get_unprocessed_cgi {
 6920:   my ($query,$possible_names)= @_;
 6921:   # $Apache::lonxml::debug=1;
 6922:   foreach my $pair (split(/&/,$query)) {
 6923:     my ($name, $value) = split(/=/,$pair);
 6924:     $name = &unescape($name);
 6925:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 6926:       $value =~ tr/+/ /;
 6927:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 6928:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 6929:     }
 6930:   }
 6931: }
 6932: 
 6933: =pod
 6934: 
 6935: =item * &cacheheader() 
 6936: 
 6937: returns cache-controlling header code
 6938: 
 6939: =cut
 6940: 
 6941: sub cacheheader {
 6942:     unless ($env{'request.method'} eq 'GET') { return ''; }
 6943:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 6944:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 6945:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 6946:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 6947:     return $output;
 6948: }
 6949: 
 6950: =pod
 6951: 
 6952: =item * &no_cache($r) 
 6953: 
 6954: specifies header code to not have cache
 6955: 
 6956: =cut
 6957: 
 6958: sub no_cache {
 6959:     my ($r) = @_;
 6960:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 6961: 	$env{'request.method'} ne 'GET') { return ''; }
 6962:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 6963:     $r->no_cache(1);
 6964:     $r->header_out("Expires" => $date);
 6965:     $r->header_out("Pragma" => "no-cache");
 6966: }
 6967: 
 6968: sub content_type {
 6969:     my ($r,$type,$charset) = @_;
 6970:     if ($r) {
 6971: 	#  Note that printout.pl calls this with undef for $r.
 6972: 	&no_cache($r);
 6973:     }
 6974:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 6975:     unless ($charset) {
 6976: 	$charset=&Apache::lonlocal::current_encoding;
 6977:     }
 6978:     if ($charset) { $type.='; charset='.$charset; }
 6979:     if ($r) {
 6980: 	$r->content_type($type);
 6981:     } else {
 6982: 	print("Content-type: $type\n\n");
 6983:     }
 6984: }
 6985: 
 6986: =pod
 6987: 
 6988: =item * &add_to_env($name,$value) 
 6989: 
 6990: adds $name to the %env hash with value
 6991: $value, if $name already exists, the entry is converted to an array
 6992: reference and $value is added to the array.
 6993: 
 6994: =cut
 6995: 
 6996: sub add_to_env {
 6997:   my ($name,$value)=@_;
 6998:   if (defined($env{$name})) {
 6999:     if (ref($env{$name})) {
 7000:       #already have multiple values
 7001:       push(@{ $env{$name} },$value);
 7002:     } else {
 7003:       #first time seeing multiple values, convert hash entry to an arrayref
 7004:       my $first=$env{$name};
 7005:       undef($env{$name});
 7006:       push(@{ $env{$name} },$first,$value);
 7007:     }
 7008:   } else {
 7009:     $env{$name}=$value;
 7010:   }
 7011: }
 7012: 
 7013: =pod
 7014: 
 7015: =item * &get_env_multiple($name) 
 7016: 
 7017: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7018: values may be defined and end up as an array ref.
 7019: 
 7020: returns an array of values
 7021: 
 7022: =cut
 7023: 
 7024: sub get_env_multiple {
 7025:     my ($name) = @_;
 7026:     my @values;
 7027:     if (defined($env{$name})) {
 7028:         # exists is it an array
 7029:         if (ref($env{$name})) {
 7030:             @values=@{ $env{$name} };
 7031:         } else {
 7032:             $values[0]=$env{$name};
 7033:         }
 7034:     }
 7035:     return(@values);
 7036: }
 7037: 
 7038: sub ask_for_embedded_content {
 7039:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7040:     my $upload_output = '
 7041:    <form name="upload_embedded" action="'.$actionurl.'"
 7042:                   method="post" enctype="multipart/form-data">';
 7043:     $upload_output .= $state;
 7044:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7045: 
 7046:     my $num = 0;
 7047:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7048:         $upload_output .= &start_data_table_row().
 7049:             '<td>'.$embed_file.'</td><td>';
 7050:         if ($args->{'ignore_remote_references'}
 7051:             && $embed_file =~ m{^\w+://}) {
 7052:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7053:         } elsif ($args->{'error_on_invalid_names'}
 7054:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7055: 
 7056:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7057: 
 7058:         } else {
 7059:             $upload_output .='
 7060:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7061:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7062:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7063:             $upload_output .=
 7064:                 "\n\t\t".
 7065:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7066:                 $attrib.'" />';
 7067:             if (exists($$codebase{$embed_file})) {
 7068:                 $upload_output .=
 7069:                     "\n\t\t".
 7070:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7071:                     &escape($$codebase{$embed_file}).'" />';
 7072:             }
 7073:         }
 7074:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7075:         $num++;
 7076:     }
 7077:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7078:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7079:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7080:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7081:    </form>';
 7082:     return $upload_output;
 7083: }
 7084: 
 7085: sub upload_embedded {
 7086:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7087:         $current_disk_usage) = @_;
 7088:     my $output;
 7089:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7090:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7091:         my $orig_uploaded_filename =
 7092:             $env{'form.embedded_item_'.$i.'.filename'};
 7093: 
 7094:         $env{'form.embedded_orig_'.$i} =
 7095:             &unescape($env{'form.embedded_orig_'.$i});
 7096:         my ($path,$fname) =
 7097:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7098:         # no path, whole string is fname
 7099:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7100: 
 7101:         $path = $env{'form.currentpath'}.$path;
 7102:         $fname = &Apache::lonnet::clean_filename($fname);
 7103:         # See if there is anything left
 7104:         next if ($fname eq '');
 7105: 
 7106:         # Check if file already exists as a file or directory.
 7107:         my ($state,$msg);
 7108:         if ($context eq 'portfolio') {
 7109:             my $port_path = $dirpath;
 7110:             if ($group ne '') {
 7111:                 $port_path = "groups/$group/$port_path";
 7112:             }
 7113:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7114:                                               $dir_root,$port_path,$disk_quota,
 7115:                                               $current_disk_usage,$uname,$udom);
 7116:             if ($state eq 'will_exceed_quota'
 7117:                 || $state eq 'file_locked'
 7118:                 || $state eq 'file_exists' ) {
 7119:                 $output .= $msg;
 7120:                 next;
 7121:             }
 7122:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7123:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7124:             if ($state eq 'exists') {
 7125:                 $output .= $msg;
 7126:                 next;
 7127:             }
 7128:         }
 7129:         # Check if extension is valid
 7130:         if (($fname =~ /\.(\w+)$/) &&
 7131:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7132:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7133:             next;
 7134:         } elsif (($fname =~ /\.(\w+)$/) &&
 7135:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7136:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7137:             next;
 7138:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7139:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7140:             next;
 7141:         }
 7142: 
 7143:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7144:         if ($context eq 'portfolio') {
 7145:             my $result=
 7146:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7147:                                                 $dirpath.$path);
 7148:             if ($result !~ m|^/uploaded/|) {
 7149:                 $output .= '<span class="LC_error">'
 7150:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7151:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7152:                       .'</span><br />';
 7153:                 next;
 7154:             } else {
 7155:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7156:                            $path.$fname.'</span>').'</p>';     
 7157:             }
 7158:         } else {
 7159: # Save the file
 7160:             my $target = $env{'form.embedded_item_'.$i};
 7161:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7162:             my $dest = $fullpath.$fname;
 7163:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7164:             my @parts=split(/\//,$fullpath);
 7165:             my $count;
 7166:             my $filepath = $dir_root;
 7167:             for ($count=4;$count<=$#parts;$count++) {
 7168:                 $filepath .= "/$parts[$count]";
 7169:                 if ((-e $filepath)!=1) {
 7170:                     mkdir($filepath,0770);
 7171:                 }
 7172:             }
 7173:             my $fh;
 7174:             if (!open($fh,'>'.$dest)) {
 7175:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7176:                 $output .= '<span class="LC_error">'.
 7177:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7178:                            '</span><br />';
 7179:             } else {
 7180:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7181:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7182:                     $output .= '<span class="LC_error">'.
 7183:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7184:                               '</span><br />';
 7185:                 } else {
 7186:                     if ($context eq 'testbank') {
 7187:                         $output .= &mt('Embedded file uploaded successfully:').
 7188:                                    '&nbsp;<a href="'.$url.'">'.
 7189:                                    $orig_uploaded_filename.'</a><br />';
 7190:                     } else {
 7191:                         $output .= '<font size="+2">'.
 7192:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7193:                                    $orig_uploaded_filename.'</a>').'</font><br />';
 7194:                     }
 7195:                 }
 7196:                 close($fh);
 7197:             }
 7198:         }
 7199:     }
 7200:     return $output;
 7201: }
 7202: 
 7203: sub check_for_existing {
 7204:     my ($path,$fname,$element) = @_;
 7205:     my ($state,$msg);
 7206:     if (-d $path.'/'.$fname) {
 7207:         $state = 'exists';
 7208:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7209:     } elsif (-e $path.'/'.$fname) {
 7210:         $state = 'exists';
 7211:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7212:     }
 7213:     if ($state eq 'exists') {
 7214:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7215:     }
 7216:     return ($state,$msg);
 7217: }
 7218: 
 7219: sub check_for_upload {
 7220:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7221:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7222:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7223:     my $getpropath = 1;
 7224:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7225:                                             $getpropath);
 7226:     my $found_file = 0;
 7227:     my $locked_file = 0;
 7228:     foreach my $line (@dir_list) {
 7229:         my ($file_name)=split(/\&/,$line,2);
 7230:         if ($file_name eq $fname){
 7231:             $file_name = $path.$file_name;
 7232:             if ($group ne '') {
 7233:                 $file_name = $group.$file_name;
 7234:             }
 7235:             $found_file = 1;
 7236:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7237:                 $locked_file = 1;
 7238:             }
 7239:         }
 7240:     }
 7241:     my $getpropath = 1;
 7242:     if (($current_disk_usage + $filesize) > $disk_quota){
 7243:         my $msg = '<span class="LC_error">'.
 7244:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7245:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7246:         return ('will_exceed_quota',$msg);
 7247:     } elsif ($found_file) {
 7248:         if ($locked_file) {
 7249:             my $msg = '<span class="LC_error">';
 7250:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
 7251:             $msg .= '</span><br />';
 7252:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7253:             return ('file_locked',$msg);
 7254:         } else {
 7255:             my $msg = '<span class="LC_error">';
 7256:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 7257:             $msg .= '</span>';
 7258:             $msg .= '<br />';
 7259:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7260:             return ('file_exists',$msg);
 7261:         }
 7262:     }
 7263: }
 7264: 
 7265: 
 7266: =pod
 7267: 
 7268: =back
 7269: 
 7270: =head1 CSV Upload/Handling functions
 7271: 
 7272: =over 4
 7273: 
 7274: =item * &upfile_store($r)
 7275: 
 7276: Store uploaded file, $r should be the HTTP Request object,
 7277: needs $env{'form.upfile'}
 7278: returns $datatoken to be put into hidden field
 7279: 
 7280: =cut
 7281: 
 7282: sub upfile_store {
 7283:     my $r=shift;
 7284:     $env{'form.upfile'}=~s/\r/\n/gs;
 7285:     $env{'form.upfile'}=~s/\f/\n/gs;
 7286:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7287:     $env{'form.upfile'}=~s/\n+$//gs;
 7288: 
 7289:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7290: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7291:     {
 7292:         my $datafile = $r->dir_config('lonDaemons').
 7293:                            '/tmp/'.$datatoken.'.tmp';
 7294:         if ( open(my $fh,">$datafile") ) {
 7295:             print $fh $env{'form.upfile'};
 7296:             close($fh);
 7297:         }
 7298:     }
 7299:     return $datatoken;
 7300: }
 7301: 
 7302: =pod
 7303: 
 7304: =item * &load_tmp_file($r)
 7305: 
 7306: Load uploaded file from tmp, $r should be the HTTP Request object,
 7307: needs $env{'form.datatoken'},
 7308: sets $env{'form.upfile'} to the contents of the file
 7309: 
 7310: =cut
 7311: 
 7312: sub load_tmp_file {
 7313:     my $r=shift;
 7314:     my @studentdata=();
 7315:     {
 7316:         my $studentfile = $r->dir_config('lonDaemons').
 7317:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7318:         if ( open(my $fh,"<$studentfile") ) {
 7319:             @studentdata=<$fh>;
 7320:             close($fh);
 7321:         }
 7322:     }
 7323:     $env{'form.upfile'}=join('',@studentdata);
 7324: }
 7325: 
 7326: =pod
 7327: 
 7328: =item * &upfile_record_sep()
 7329: 
 7330: Separate uploaded file into records
 7331: returns array of records,
 7332: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7333: 
 7334: =cut
 7335: 
 7336: sub upfile_record_sep {
 7337:     if ($env{'form.upfiletype'} eq 'xml') {
 7338:     } else {
 7339: 	my @records;
 7340: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7341: 	    if ($line=~/^\s*$/) { next; }
 7342: 	    push(@records,$line);
 7343: 	}
 7344: 	return @records;
 7345:     }
 7346: }
 7347: 
 7348: =pod
 7349: 
 7350: =item * &record_sep($record)
 7351: 
 7352: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7353: 
 7354: =cut
 7355: 
 7356: sub takeleft {
 7357:     my $index=shift;
 7358:     return substr('0000'.$index,-4,4);
 7359: }
 7360: 
 7361: sub record_sep {
 7362:     my $record=shift;
 7363:     my %components=();
 7364:     if ($env{'form.upfiletype'} eq 'xml') {
 7365:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7366:         my $i=0;
 7367:         foreach my $field (split(/\s+/,$record)) {
 7368:             $field=~s/^(\"|\')//;
 7369:             $field=~s/(\"|\')$//;
 7370:             $components{&takeleft($i)}=$field;
 7371:             $i++;
 7372:         }
 7373:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7374:         my $i=0;
 7375:         foreach my $field (split(/\t/,$record)) {
 7376:             $field=~s/^(\"|\')//;
 7377:             $field=~s/(\"|\')$//;
 7378:             $components{&takeleft($i)}=$field;
 7379:             $i++;
 7380:         }
 7381:     } else {
 7382:         my $separator=',';
 7383:         if ($env{'form.upfiletype'} eq 'semisv') {
 7384:             $separator=';';
 7385:         }
 7386:         my $i=0;
 7387: # the character we are looking for to indicate the end of a quote or a record 
 7388:         my $looking_for=$separator;
 7389: # do not add the characters to the fields
 7390:         my $ignore=0;
 7391: # we just encountered a separator (or the beginning of the record)
 7392:         my $just_found_separator=1;
 7393: # store the field we are working on here
 7394:         my $field='';
 7395: # work our way through all characters in record
 7396:         foreach my $character ($record=~/(.)/g) {
 7397:             if ($character eq $looking_for) {
 7398:                if ($character ne $separator) {
 7399: # Found the end of a quote, again looking for separator
 7400:                   $looking_for=$separator;
 7401:                   $ignore=1;
 7402:                } else {
 7403: # Found a separator, store away what we got
 7404:                   $components{&takeleft($i)}=$field;
 7405: 	          $i++;
 7406:                   $just_found_separator=1;
 7407:                   $ignore=0;
 7408:                   $field='';
 7409:                }
 7410:                next;
 7411:             }
 7412: # single or double quotation marks after a separator indicate beginning of a quote
 7413: # we are now looking for the end of the quote and need to ignore separators
 7414:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7415:                $looking_for=$character;
 7416:                next;
 7417:             }
 7418: # ignore would be true after we reached the end of a quote
 7419:             if ($ignore) { next; }
 7420:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7421:             $field.=$character;
 7422:             $just_found_separator=0; 
 7423:         }
 7424: # catch the very last entry, since we never encountered the separator
 7425:         $components{&takeleft($i)}=$field;
 7426:     }
 7427:     return %components;
 7428: }
 7429: 
 7430: ######################################################
 7431: ######################################################
 7432: 
 7433: =pod
 7434: 
 7435: =item * &upfile_select_html()
 7436: 
 7437: Return HTML code to select a file from the users machine and specify 
 7438: the file type.
 7439: 
 7440: =cut
 7441: 
 7442: ######################################################
 7443: ######################################################
 7444: sub upfile_select_html {
 7445:     my %Types = (
 7446:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7447:                  semisv => &mt('Semicolon separated values'),
 7448:                  space => &mt('Space separated'),
 7449:                  tab   => &mt('Tabulator separated'),
 7450: #                 xml   => &mt('HTML/XML'),
 7451:                  );
 7452:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7453:         '<br />Type: <select name="upfiletype">';
 7454:     foreach my $type (sort(keys(%Types))) {
 7455:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7456:     }
 7457:     $Str .= "</select>\n";
 7458:     return $Str;
 7459: }
 7460: 
 7461: sub get_samples {
 7462:     my ($records,$toget) = @_;
 7463:     my @samples=({});
 7464:     my $got=0;
 7465:     foreach my $rec (@$records) {
 7466: 	my %temp = &record_sep($rec);
 7467: 	if (! grep(/\S/, values(%temp))) { next; }
 7468: 	if (%temp) {
 7469: 	    $samples[$got]=\%temp;
 7470: 	    $got++;
 7471: 	    if ($got == $toget) { last; }
 7472: 	}
 7473:     }
 7474:     return \@samples;
 7475: }
 7476: 
 7477: ######################################################
 7478: ######################################################
 7479: 
 7480: =pod
 7481: 
 7482: =item * &csv_print_samples($r,$records)
 7483: 
 7484: Prints a table of sample values from each column uploaded $r is an
 7485: Apache Request ref, $records is an arrayref from
 7486: &Apache::loncommon::upfile_record_sep
 7487: 
 7488: =cut
 7489: 
 7490: ######################################################
 7491: ######################################################
 7492: sub csv_print_samples {
 7493:     my ($r,$records) = @_;
 7494:     my $samples = &get_samples($records,5);
 7495: 
 7496:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 7497:               &start_data_table_header_row());
 7498:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 7499:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 7500:     $r->print(&end_data_table_header_row());
 7501:     foreach my $hash (@$samples) {
 7502: 	$r->print(&start_data_table_row());
 7503: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7504: 	    $r->print('<td>');
 7505: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 7506: 	    $r->print('</td>');
 7507: 	}
 7508: 	$r->print(&end_data_table_row());
 7509:     }
 7510:     $r->print(&end_data_table().'<br />'."\n");
 7511: }
 7512: 
 7513: ######################################################
 7514: ######################################################
 7515: 
 7516: =pod
 7517: 
 7518: =item * &csv_print_select_table($r,$records,$d)
 7519: 
 7520: Prints a table to create associations between values and table columns.
 7521: 
 7522: $r is an Apache Request ref,
 7523: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7524: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 7525: 
 7526: =cut
 7527: 
 7528: ######################################################
 7529: ######################################################
 7530: sub csv_print_select_table {
 7531:     my ($r,$records,$d) = @_;
 7532:     my $i=0;
 7533:     my $samples = &get_samples($records,1);
 7534:     $r->print(&mt('Associate columns with student attributes.')."\n".
 7535: 	      &start_data_table().&start_data_table_header_row().
 7536:               '<th>'.&mt('Attribute').'</th>'.
 7537:               '<th>'.&mt('Column').'</th>'.
 7538:               &end_data_table_header_row()."\n");
 7539:     foreach my $array_ref (@$d) {
 7540: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 7541: 	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
 7542: 
 7543: 	$r->print('<td><select name=f'.$i.
 7544: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7545: 	$r->print('<option value="none"></option>');
 7546: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7547: 	    $r->print('<option value="'.$sample.'"'.
 7548:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 7549:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 7550: 	}
 7551: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 7552: 	$i++;
 7553:     }
 7554:     $r->print(&end_data_table());
 7555:     $i--;
 7556:     return $i;
 7557: }
 7558: 
 7559: ######################################################
 7560: ######################################################
 7561: 
 7562: =pod
 7563: 
 7564: =item * &csv_samples_select_table($r,$records,$d)
 7565: 
 7566: Prints a table of sample values from the upload and can make associate samples to internal names.
 7567: 
 7568: $r is an Apache Request ref,
 7569: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7570: $d is an array of 2 element arrays (internal name, displayed name)
 7571: 
 7572: =cut
 7573: 
 7574: ######################################################
 7575: ######################################################
 7576: sub csv_samples_select_table {
 7577:     my ($r,$records,$d) = @_;
 7578:     my $i=0;
 7579:     #
 7580:     my $max_samples = 5;
 7581:     my $samples = &get_samples($records,$max_samples);
 7582:     $r->print(&start_data_table().
 7583:               &start_data_table_header_row().'<th>'.
 7584:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 7585:               &end_data_table_header_row());
 7586: 
 7587:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 7588: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 7589: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7590: 	foreach my $option (@$d) {
 7591: 	    my ($value,$display,$defaultcol)=@{ $option };
 7592: 	    $r->print('<option value="'.$value.'"'.
 7593:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 7594:                       $display.'</option>');
 7595: 	}
 7596: 	$r->print('</select></td><td>');
 7597: 	foreach my $line (0..($max_samples-1)) {
 7598: 	    if (defined($samples->[$line]{$key})) { 
 7599: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 7600: 	    }
 7601: 	}
 7602: 	$r->print('</td>'.&end_data_table_row());
 7603: 	$i++;
 7604:     }
 7605:     $r->print(&end_data_table());
 7606:     $i--;
 7607:     return($i);
 7608: }
 7609: 
 7610: ######################################################
 7611: ######################################################
 7612: 
 7613: =pod
 7614: 
 7615: =item * &clean_excel_name($name)
 7616: 
 7617: Returns a replacement for $name which does not contain any illegal characters.
 7618: 
 7619: =cut
 7620: 
 7621: ######################################################
 7622: ######################################################
 7623: sub clean_excel_name {
 7624:     my ($name) = @_;
 7625:     $name =~ s/[:\*\?\/\\]//g;
 7626:     if (length($name) > 31) {
 7627:         $name = substr($name,0,31);
 7628:     }
 7629:     return $name;
 7630: }
 7631: 
 7632: =pod
 7633: 
 7634: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 7635: 
 7636: Returns either 1 or undef
 7637: 
 7638: 1 if the part is to be hidden, undef if it is to be shown
 7639: 
 7640: Arguments are:
 7641: 
 7642: $id the id of the part to be checked
 7643: $symb, optional the symb of the resource to check
 7644: $udom, optional the domain of the user to check for
 7645: $uname, optional the username of the user to check for
 7646: 
 7647: =cut
 7648: 
 7649: sub check_if_partid_hidden {
 7650:     my ($id,$symb,$udom,$uname) = @_;
 7651:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 7652: 					 $symb,$udom,$uname);
 7653:     my $truth=1;
 7654:     #if the string starts with !, then the list is the list to show not hide
 7655:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 7656:     my @hiddenlist=split(/,/,$hiddenparts);
 7657:     foreach my $checkid (@hiddenlist) {
 7658: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 7659:     }
 7660:     return !$truth;
 7661: }
 7662: 
 7663: 
 7664: ############################################################
 7665: ############################################################
 7666: 
 7667: =pod
 7668: 
 7669: =back 
 7670: 
 7671: =head1 cgi-bin script and graphing routines
 7672: 
 7673: =over 4
 7674: 
 7675: =item * &get_cgi_id()
 7676: 
 7677: Inputs: none
 7678: 
 7679: Returns an id which can be used to pass environment variables
 7680: to various cgi-bin scripts.  These environment variables will
 7681: be removed from the users environment after a given time by
 7682: the routine &Apache::lonnet::transfer_profile_to_env.
 7683: 
 7684: =cut
 7685: 
 7686: ############################################################
 7687: ############################################################
 7688: my $uniq=0;
 7689: sub get_cgi_id {
 7690:     $uniq=($uniq+1)%100000;
 7691:     return (time.'_'.$$.'_'.$uniq);
 7692: }
 7693: 
 7694: ############################################################
 7695: ############################################################
 7696: 
 7697: =pod
 7698: 
 7699: =item * &DrawBarGraph()
 7700: 
 7701: Facilitates the plotting of data in a (stacked) bar graph.
 7702: Puts plot definition data into the users environment in order for 
 7703: graph.png to plot it.  Returns an <img> tag for the plot.
 7704: The bars on the plot are labeled '1','2',...,'n'.
 7705: 
 7706: Inputs:
 7707: 
 7708: =over 4
 7709: 
 7710: =item $Title: string, the title of the plot
 7711: 
 7712: =item $xlabel: string, text describing the X-axis of the plot
 7713: 
 7714: =item $ylabel: string, text describing the Y-axis of the plot
 7715: 
 7716: =item $Max: scalar, the maximum Y value to use in the plot
 7717: If $Max is < any data point, the graph will not be rendered.
 7718: 
 7719: =item $colors: array ref holding the colors to be used for the data sets when
 7720: they are plotted.  If undefined, default values will be used.
 7721: 
 7722: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 7723: 
 7724: =item @Values: An array of array references.  Each array reference holds data
 7725: to be plotted in a stacked bar chart.
 7726: 
 7727: =item If the final element of @Values is a hash reference the key/value
 7728: pairs will be added to the graph definition.
 7729: 
 7730: =back
 7731: 
 7732: Returns:
 7733: 
 7734: An <img> tag which references graph.png and the appropriate identifying
 7735: information for the plot.
 7736: 
 7737: =cut
 7738: 
 7739: ############################################################
 7740: ############################################################
 7741: sub DrawBarGraph {
 7742:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 7743:     #
 7744:     if (! defined($colors)) {
 7745:         $colors = ['#33ff00', 
 7746:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 7747:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 7748:                   ]; 
 7749:     }
 7750:     my $extra_settings = {};
 7751:     if (ref($Values[-1]) eq 'HASH') {
 7752:         $extra_settings = pop(@Values);
 7753:     }
 7754:     #
 7755:     my $identifier = &get_cgi_id();
 7756:     my $id = 'cgi.'.$identifier;        
 7757:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 7758:         return '';
 7759:     }
 7760:     #
 7761:     my @Labels;
 7762:     if (defined($labels)) {
 7763:         @Labels = @$labels;
 7764:     } else {
 7765:         for (my $i=0;$i<@{$Values[0]};$i++) {
 7766:             push (@Labels,$i+1);
 7767:         }
 7768:     }
 7769:     #
 7770:     my $NumBars = scalar(@{$Values[0]});
 7771:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 7772:     my %ValuesHash;
 7773:     my $NumSets=1;
 7774:     foreach my $array (@Values) {
 7775:         next if (! ref($array));
 7776:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 7777:             join(',',@$array);
 7778:     }
 7779:     #
 7780:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 7781:     if ($NumBars < 3) {
 7782:         $width = 120+$NumBars*32;
 7783:         $xskip = 1;
 7784:         $bar_width = 30;
 7785:     } elsif ($NumBars < 5) {
 7786:         $width = 120+$NumBars*20;
 7787:         $xskip = 1;
 7788:         $bar_width = 20;
 7789:     } elsif ($NumBars < 10) {
 7790:         $width = 120+$NumBars*15;
 7791:         $xskip = 1;
 7792:         $bar_width = 15;
 7793:     } elsif ($NumBars <= 25) {
 7794:         $width = 120+$NumBars*11;
 7795:         $xskip = 5;
 7796:         $bar_width = 8;
 7797:     } elsif ($NumBars <= 50) {
 7798:         $width = 120+$NumBars*8;
 7799:         $xskip = 5;
 7800:         $bar_width = 4;
 7801:     } else {
 7802:         $width = 120+$NumBars*8;
 7803:         $xskip = 5;
 7804:         $bar_width = 4;
 7805:     }
 7806:     #
 7807:     $Max = 1 if ($Max < 1);
 7808:     if ( int($Max) < $Max ) {
 7809:         $Max++;
 7810:         $Max = int($Max);
 7811:     }
 7812:     $Title  = '' if (! defined($Title));
 7813:     $xlabel = '' if (! defined($xlabel));
 7814:     $ylabel = '' if (! defined($ylabel));
 7815:     $ValuesHash{$id.'.title'}    = &escape($Title);
 7816:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 7817:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 7818:     $ValuesHash{$id.'.y_max_value'} = $Max;
 7819:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 7820:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 7821:     $ValuesHash{$id.'.PlotType'} = 'bar';
 7822:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7823:     $ValuesHash{$id.'.height'}   = $height;
 7824:     $ValuesHash{$id.'.width'}    = $width;
 7825:     $ValuesHash{$id.'.xskip'}    = $xskip;
 7826:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 7827:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 7828:     #
 7829:     # Deal with other parameters
 7830:     while (my ($key,$value) = each(%$extra_settings)) {
 7831:         $ValuesHash{$id.'.'.$key} = $value;
 7832:     }
 7833:     #
 7834:     &Apache::lonnet::appenv(\%ValuesHash);
 7835:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7836: }
 7837: 
 7838: ############################################################
 7839: ############################################################
 7840: 
 7841: =pod
 7842: 
 7843: =item * &DrawXYGraph()
 7844: 
 7845: Facilitates the plotting of data in an XY graph.
 7846: Puts plot definition data into the users environment in order for 
 7847: graph.png to plot it.  Returns an <img> tag for the plot.
 7848: 
 7849: Inputs:
 7850: 
 7851: =over 4
 7852: 
 7853: =item $Title: string, the title of the plot
 7854: 
 7855: =item $xlabel: string, text describing the X-axis of the plot
 7856: 
 7857: =item $ylabel: string, text describing the Y-axis of the plot
 7858: 
 7859: =item $Max: scalar, the maximum Y value to use in the plot
 7860: If $Max is < any data point, the graph will not be rendered.
 7861: 
 7862: =item $colors: Array ref containing the hex color codes for the data to be 
 7863: plotted in.  If undefined, default values will be used.
 7864: 
 7865: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7866: 
 7867: =item $Ydata: Array ref containing Array refs.  
 7868: Each of the contained arrays will be plotted as a separate curve.
 7869: 
 7870: =item %Values: hash indicating or overriding any default values which are 
 7871: passed to graph.png.  
 7872: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7873: 
 7874: =back
 7875: 
 7876: Returns:
 7877: 
 7878: An <img> tag which references graph.png and the appropriate identifying
 7879: information for the plot.
 7880: 
 7881: =cut
 7882: 
 7883: ############################################################
 7884: ############################################################
 7885: sub DrawXYGraph {
 7886:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 7887:     #
 7888:     # Create the identifier for the graph
 7889:     my $identifier = &get_cgi_id();
 7890:     my $id = 'cgi.'.$identifier;
 7891:     #
 7892:     $Title  = '' if (! defined($Title));
 7893:     $xlabel = '' if (! defined($xlabel));
 7894:     $ylabel = '' if (! defined($ylabel));
 7895:     my %ValuesHash = 
 7896:         (
 7897:          $id.'.title'  => &escape($Title),
 7898:          $id.'.xlabel' => &escape($xlabel),
 7899:          $id.'.ylabel' => &escape($ylabel),
 7900:          $id.'.y_max_value'=> $Max,
 7901:          $id.'.labels'     => join(',',@$Xlabels),
 7902:          $id.'.PlotType'   => 'XY',
 7903:          );
 7904:     #
 7905:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 7906:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7907:     }
 7908:     #
 7909:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 7910:         return '';
 7911:     }
 7912:     my $NumSets=1;
 7913:     foreach my $array (@{$Ydata}){
 7914:         next if (! ref($array));
 7915:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 7916:     }
 7917:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 7918:     #
 7919:     # Deal with other parameters
 7920:     while (my ($key,$value) = each(%Values)) {
 7921:         $ValuesHash{$id.'.'.$key} = $value;
 7922:     }
 7923:     #
 7924:     &Apache::lonnet::appenv(\%ValuesHash);
 7925:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7926: }
 7927: 
 7928: ############################################################
 7929: ############################################################
 7930: 
 7931: =pod
 7932: 
 7933: =item * &DrawXYYGraph()
 7934: 
 7935: Facilitates the plotting of data in an XY graph with two Y axes.
 7936: Puts plot definition data into the users environment in order for 
 7937: graph.png to plot it.  Returns an <img> tag for the plot.
 7938: 
 7939: Inputs:
 7940: 
 7941: =over 4
 7942: 
 7943: =item $Title: string, the title of the plot
 7944: 
 7945: =item $xlabel: string, text describing the X-axis of the plot
 7946: 
 7947: =item $ylabel: string, text describing the Y-axis of the plot
 7948: 
 7949: =item $colors: Array ref containing the hex color codes for the data to be 
 7950: plotted in.  If undefined, default values will be used.
 7951: 
 7952: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7953: 
 7954: =item $Ydata1: The first data set
 7955: 
 7956: =item $Min1: The minimum value of the left Y-axis
 7957: 
 7958: =item $Max1: The maximum value of the left Y-axis
 7959: 
 7960: =item $Ydata2: The second data set
 7961: 
 7962: =item $Min2: The minimum value of the right Y-axis
 7963: 
 7964: =item $Max2: The maximum value of the left Y-axis
 7965: 
 7966: =item %Values: hash indicating or overriding any default values which are 
 7967: passed to graph.png.  
 7968: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7969: 
 7970: =back
 7971: 
 7972: Returns:
 7973: 
 7974: An <img> tag which references graph.png and the appropriate identifying
 7975: information for the plot.
 7976: 
 7977: =cut
 7978: 
 7979: ############################################################
 7980: ############################################################
 7981: sub DrawXYYGraph {
 7982:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 7983:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 7984:     #
 7985:     # Create the identifier for the graph
 7986:     my $identifier = &get_cgi_id();
 7987:     my $id = 'cgi.'.$identifier;
 7988:     #
 7989:     $Title  = '' if (! defined($Title));
 7990:     $xlabel = '' if (! defined($xlabel));
 7991:     $ylabel = '' if (! defined($ylabel));
 7992:     my %ValuesHash = 
 7993:         (
 7994:          $id.'.title'  => &escape($Title),
 7995:          $id.'.xlabel' => &escape($xlabel),
 7996:          $id.'.ylabel' => &escape($ylabel),
 7997:          $id.'.labels' => join(',',@$Xlabels),
 7998:          $id.'.PlotType' => 'XY',
 7999:          $id.'.NumSets' => 2,
 8000:          $id.'.two_axes' => 1,
 8001:          $id.'.y1_max_value' => $Max1,
 8002:          $id.'.y1_min_value' => $Min1,
 8003:          $id.'.y2_max_value' => $Max2,
 8004:          $id.'.y2_min_value' => $Min2,
 8005:          );
 8006:     #
 8007:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8008:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8009:     }
 8010:     #
 8011:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8012:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8013:         return '';
 8014:     }
 8015:     my $NumSets=1;
 8016:     foreach my $array ($Ydata1,$Ydata2){
 8017:         next if (! ref($array));
 8018:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8019:     }
 8020:     #
 8021:     # Deal with other parameters
 8022:     while (my ($key,$value) = each(%Values)) {
 8023:         $ValuesHash{$id.'.'.$key} = $value;
 8024:     }
 8025:     #
 8026:     &Apache::lonnet::appenv(\%ValuesHash);
 8027:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8028: }
 8029: 
 8030: ############################################################
 8031: ############################################################
 8032: 
 8033: =pod
 8034: 
 8035: =back 
 8036: 
 8037: =head1 Statistics helper routines?  
 8038: 
 8039: Bad place for them but what the hell.
 8040: 
 8041: =over 4
 8042: 
 8043: =item * &chartlink()
 8044: 
 8045: Returns a link to the chart for a specific student.  
 8046: 
 8047: Inputs:
 8048: 
 8049: =over 4
 8050: 
 8051: =item $linktext: The text of the link
 8052: 
 8053: =item $sname: The students username
 8054: 
 8055: =item $sdomain: The students domain
 8056: 
 8057: =back
 8058: 
 8059: =back
 8060: 
 8061: =cut
 8062: 
 8063: ############################################################
 8064: ############################################################
 8065: sub chartlink {
 8066:     my ($linktext, $sname, $sdomain) = @_;
 8067:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8068:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8069:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8070:        '">'.$linktext.'</a>';
 8071: }
 8072: 
 8073: #######################################################
 8074: #######################################################
 8075: 
 8076: =pod
 8077: 
 8078: =head1 Course Environment Routines
 8079: 
 8080: =over 4
 8081: 
 8082: =item * &restore_course_settings()
 8083: 
 8084: =item * &store_course_settings()
 8085: 
 8086: Restores/Store indicated form parameters from the course environment.
 8087: Will not overwrite existing values of the form parameters.
 8088: 
 8089: Inputs: 
 8090: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8091: 
 8092: a hash ref describing the data to be stored.  For example:
 8093:    
 8094: %Save_Parameters = ('Status' => 'scalar',
 8095:     'chartoutputmode' => 'scalar',
 8096:     'chartoutputdata' => 'scalar',
 8097:     'Section' => 'array',
 8098:     'Group' => 'array',
 8099:     'StudentData' => 'array',
 8100:     'Maps' => 'array');
 8101: 
 8102: Returns: both routines return nothing
 8103: 
 8104: =back
 8105: 
 8106: =cut
 8107: 
 8108: #######################################################
 8109: #######################################################
 8110: sub store_course_settings {
 8111:     return &store_settings($env{'request.course.id'},@_);
 8112: }
 8113: 
 8114: sub store_settings {
 8115:     # save to the environment
 8116:     # appenv the same items, just to be safe
 8117:     my $udom  = $env{'user.domain'};
 8118:     my $uname = $env{'user.name'};
 8119:     my ($context,$prefix,$Settings) = @_;
 8120:     my %SaveHash;
 8121:     my %AppHash;
 8122:     while (my ($setting,$type) = each(%$Settings)) {
 8123:         my $basename = join('.','internal',$context,$prefix,$setting);
 8124:         my $envname = 'environment.'.$basename;
 8125:         if (exists($env{'form.'.$setting})) {
 8126:             # Save this value away
 8127:             if ($type eq 'scalar' &&
 8128:                 (! exists($env{$envname}) || 
 8129:                  $env{$envname} ne $env{'form.'.$setting})) {
 8130:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8131:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8132:             } elsif ($type eq 'array') {
 8133:                 my $stored_form;
 8134:                 if (ref($env{'form.'.$setting})) {
 8135:                     $stored_form = join(',',
 8136:                                         map {
 8137:                                             &escape($_);
 8138:                                         } sort(@{$env{'form.'.$setting}}));
 8139:                 } else {
 8140:                     $stored_form = 
 8141:                         &escape($env{'form.'.$setting});
 8142:                 }
 8143:                 # Determine if the array contents are the same.
 8144:                 if ($stored_form ne $env{$envname}) {
 8145:                     $SaveHash{$basename} = $stored_form;
 8146:                     $AppHash{$envname}   = $stored_form;
 8147:                 }
 8148:             }
 8149:         }
 8150:     }
 8151:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8152:                                           $udom,$uname);
 8153:     if ($put_result !~ /^(ok|delayed)/) {
 8154:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8155:                                  'got error:'.$put_result);
 8156:     }
 8157:     # Make sure these settings stick around in this session, too
 8158:     &Apache::lonnet::appenv(\%AppHash);
 8159:     return;
 8160: }
 8161: 
 8162: sub restore_course_settings {
 8163:     return &restore_settings($env{'request.course.id'},@_);
 8164: }
 8165: 
 8166: sub restore_settings {
 8167:     my ($context,$prefix,$Settings) = @_;
 8168:     while (my ($setting,$type) = each(%$Settings)) {
 8169:         next if (exists($env{'form.'.$setting}));
 8170:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8171:             '.'.$setting;
 8172:         if (exists($env{$envname})) {
 8173:             if ($type eq 'scalar') {
 8174:                 $env{'form.'.$setting} = $env{$envname};
 8175:             } elsif ($type eq 'array') {
 8176:                 $env{'form.'.$setting} = [ 
 8177:                                            map { 
 8178:                                                &unescape($_); 
 8179:                                            } split(',',$env{$envname})
 8180:                                            ];
 8181:             }
 8182:         }
 8183:     }
 8184: }
 8185: 
 8186: #######################################################
 8187: #######################################################
 8188: 
 8189: =pod
 8190: 
 8191: =head1 Domain E-mail Routines  
 8192: 
 8193: =over 4
 8194: 
 8195: =item * &build_recipient_list()
 8196: 
 8197: Build recipient lists for three types of e-mail:
 8198: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
 8199: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
 8200: 
 8201: Inputs:
 8202: defmail (scalar - email address of default recipient), 
 8203: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8204: defdom (domain for which to retrieve configuration settings),
 8205: origmail (scalar - email address of recipient from loncapa.conf, 
 8206: i.e., predates configuration by DC via domainprefs.pm 
 8207: 
 8208: Returns: comma separated list of addresses to which to send e-mail.
 8209: 
 8210: =back
 8211: 
 8212: =cut
 8213: 
 8214: ############################################################
 8215: ############################################################
 8216: sub build_recipient_list {
 8217:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8218:     my @recipients;
 8219:     my $otheremails;
 8220:     my %domconfig =
 8221:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8222:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8223:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8224:             my @contacts = ('adminemail','supportemail');
 8225:             foreach my $item (@contacts) {
 8226:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
 8227:                     my $addr = $domconfig{'contacts'}{$item}; 
 8228:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
 8229:                         push(@recipients,$addr);
 8230:                     }
 8231:                 }
 8232:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8233:             }
 8234:         }
 8235:     } elsif ($origmail ne '') {
 8236:         push(@recipients,$origmail);
 8237:     }
 8238:     if ($defmail ne '') {
 8239:         push(@recipients,$defmail);
 8240:     }
 8241:     if ($otheremails) {
 8242:         my @others;
 8243:         if ($otheremails =~ /,/) {
 8244:             @others = split(/,/,$otheremails);
 8245:         } else {
 8246:             push(@others,$otheremails);
 8247:         }
 8248:         foreach my $addr (@others) {
 8249:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8250:                 push(@recipients,$addr);
 8251:             }
 8252:         }
 8253:     }
 8254:     my $recipientlist = join(',',@recipients); 
 8255:     return $recipientlist;
 8256: }
 8257: 
 8258: ############################################################
 8259: ############################################################
 8260: 
 8261: =pod
 8262: 
 8263: =head1 Course Catalog Routines
 8264: 
 8265: =over 4
 8266: 
 8267: =item * &gather_categories()
 8268: 
 8269: Converts category definitions - keys of categories hash stored in  
 8270: coursecategories in configuration.db on the primary library server in a 
 8271: domain - to an array.  Also generates javascript and idx hash used to 
 8272: generate Domain Coordinator interface for editing Course Categories.
 8273: 
 8274: Inputs:
 8275: 
 8276: categories (reference to hash of category definitions).
 8277: 
 8278: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8279:       categories and subcategories).
 8280: 
 8281: idx (reference to hash of counters used in Domain Coordinator interface for 
 8282:       editing Course Categories).
 8283: 
 8284: jsarray (reference to array of categories used to create Javascript arrays for
 8285:          Domain Coordinator interface for editing Course Categories).
 8286: 
 8287: Returns: nothing
 8288: 
 8289: Side effects: populates cats, idx and jsarray. 
 8290: 
 8291: =cut
 8292: 
 8293: sub gather_categories {
 8294:     my ($categories,$cats,$idx,$jsarray) = @_;
 8295:     my %counters;
 8296:     my $num = 0;
 8297:     foreach my $item (keys(%{$categories})) {
 8298:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8299:         if ($container eq '' && $depth == 0) {
 8300:             $cats->[$depth][$categories->{$item}] = $cat;
 8301:         } else {
 8302:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8303:         }
 8304:         my ($escitem,$tail) = split(/:/,$item,2);
 8305:         if ($counters{$tail} eq '') {
 8306:             $counters{$tail} = $num;
 8307:             $num ++;
 8308:         }
 8309:         if (ref($idx) eq 'HASH') {
 8310:             $idx->{$item} = $counters{$tail};
 8311:         }
 8312:         if (ref($jsarray) eq 'ARRAY') {
 8313:             push(@{$jsarray->[$counters{$tail}]},$item);
 8314:         }
 8315:     }
 8316:     return;
 8317: }
 8318: 
 8319: =pod
 8320: 
 8321: =item * &extract_categories()
 8322: 
 8323: Used to generate breadcrumb trails for course categories.
 8324: 
 8325: Inputs:
 8326: 
 8327: categories (reference to hash of category definitions).
 8328: 
 8329: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8330:       categories and subcategories).
 8331: 
 8332: trails (reference to array of breacrumb trails for each category).
 8333: 
 8334: allitems (reference to hash - key is category key 
 8335:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8336: 
 8337: idx (reference to hash of counters used in Domain Coordinator interface for
 8338:       editing Course Categories).
 8339: 
 8340: jsarray (reference to array of categories used to create Javascript arrays for
 8341:          Domain Coordinator interface for editing Course Categories).
 8342: 
 8343: Returns: nothing
 8344: 
 8345: Side effects: populates trails and allitems hash references.
 8346: 
 8347: =cut
 8348: 
 8349: sub extract_categories {
 8350:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray) = @_;
 8351:     if (ref($categories) eq 'HASH') {
 8352:         &gather_categories($categories,$cats,$idx,$jsarray);
 8353:         if (ref($cats->[0]) eq 'ARRAY') {
 8354:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8355:                 my $name = $cats->[0][$i];
 8356:                 my $item = &escape($name).'::0';
 8357:                 my $trailstr;
 8358:                 if ($name eq 'instcode') {
 8359:                     $trailstr = &mt('Official courses (with institutional codes)');
 8360:                 } else {
 8361:                     $trailstr = $name;
 8362:                 }
 8363:                 if ($allitems->{$item} eq '') {
 8364:                     push(@{$trails},$trailstr);
 8365:                     $allitems->{$item} = scalar(@{$trails})-1;
 8366:                 }
 8367:                 my @parents = ($name);
 8368:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8369:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8370:                         my $category = $cats->[1]{$name}[$j];
 8371:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents);
 8372:                     }
 8373:                 }
 8374:             }
 8375:         }
 8376:     }
 8377:     return;
 8378: }
 8379: 
 8380: =pod
 8381: 
 8382: =item *&recurse_categories()
 8383: 
 8384: Recursively used to generate breadcrumb trails for course categories.
 8385: 
 8386: Inputs:
 8387: 
 8388: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8389:       categories and subcategories).
 8390: 
 8391: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8392: 
 8393: category (current course category, for which breadcrumb trail is being generated).
 8394: 
 8395: trails (reference to array of breadcrumb trails for each category).
 8396: 
 8397: allitems (reference to hash - key is category key
 8398:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8399: 
 8400: parents (array containing containers directories for current category, 
 8401:          back to top level). 
 8402: 
 8403: Returns: nothing
 8404: 
 8405: Side effects: populates trails and allitems hash references
 8406: 
 8407: =cut
 8408: 
 8409: sub recurse_categories {
 8410:     my ($cats,$depth,$category,$trails,$allitems,$parents) = @_;
 8411:     my $shallower = $depth - 1;
 8412:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8413:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8414:             my $name = $cats->[$depth]{$category}[$k];
 8415:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8416:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8417:             if ($allitems->{$item} eq '') {
 8418:                 push(@{$trails},$trailstr);
 8419:                 $allitems->{$item} = scalar(@{$trails})-1;
 8420:             }
 8421:             my $deeper = $depth+1;
 8422:             push(@{$parents},$category);
 8423:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents);
 8424:             pop(@{$parents});
 8425:         }
 8426:     } else {
 8427:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8428:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8429:         if ($allitems->{$item} eq '') {
 8430:             push(@{$trails},$trailstr);
 8431:             $allitems->{$item} = scalar(@{$trails})-1;
 8432:         }
 8433:     }
 8434:     return;
 8435: }
 8436: 
 8437: =pod
 8438: 
 8439: =item *&assign_categories_table()
 8440: 
 8441: Create a datatable for display of hierarchical categories in a domain,
 8442: with checkboxes to allow a course to be categorized. 
 8443: 
 8444: Inputs:
 8445: 
 8446: cathash - reference to hash of categories defined for the domain (from
 8447:           configuration.db)
 8448: 
 8449: currcat - scalar with an & separated list of categories assigned to a course. 
 8450: 
 8451: Returns: $output (markup to be displayed) 
 8452: 
 8453: =cut
 8454: 
 8455: sub assign_categories_table {
 8456:     my ($cathash,$currcat) = @_;
 8457:     my $output;
 8458:     if (ref($cathash) eq 'HASH') {
 8459:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 8460:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 8461:         $maxdepth = scalar(@cats);
 8462:         if (@cats > 0) {
 8463:             my $itemcount = 0;
 8464:             if (ref($cats[0]) eq 'ARRAY') {
 8465:                 $output = &Apache::loncommon::start_data_table();
 8466:                 my @currcategories;
 8467:                 if ($currcat ne '') {
 8468:                     @currcategories = split('&',$currcat);
 8469:                 }
 8470:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 8471:                     my $parent = $cats[0][$i];
 8472:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8473:                     next if ($parent eq 'instcode');
 8474:                     my $item = &escape($parent).'::0';
 8475:                     my $checked = '';
 8476:                     if (@currcategories > 0) {
 8477:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 8478:                             $checked = ' checked="checked" ';
 8479:                         }
 8480:                     }
 8481:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8482:                                .'<input type="checkbox" name="usecategory" value="'.
 8483:                                $item.'"'.$checked.' />'.&escape($parent).'</span></td>';
 8484:                     my $depth = 1;
 8485:                     push(@path,$parent);
 8486:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 8487:                     pop(@path);
 8488:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8489:                     $itemcount ++;
 8490:                 }
 8491:                 $output .= &Apache::loncommon::end_data_table();
 8492:             }
 8493:         }
 8494:     }
 8495:     return $output;
 8496: }
 8497: 
 8498: =pod
 8499: 
 8500: =item *&assign_category_rows()
 8501: 
 8502: Create a datatable row for display of nested categories in a domain,
 8503: with checkboxes to allow a course to be categorized,called recursively.
 8504: 
 8505: Inputs:
 8506: 
 8507: itemcount - track row number for alternating colors
 8508: 
 8509: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 8510:       categories and subcategories.
 8511: 
 8512: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 8513: 
 8514: parent - parent of current category item
 8515: 
 8516: path - Array containing all categories back up through the hierarchy from the
 8517:        current category to the top level.
 8518: 
 8519: currcategories - reference to array of current categories assigned to the course
 8520: 
 8521: Returns: $output (markup to be displayed).
 8522: 
 8523: =cut
 8524: 
 8525: sub assign_category_rows {
 8526:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 8527:     my ($text,$name,$item,$chgstr);
 8528:     if (ref($cats) eq 'ARRAY') {
 8529:         my $maxdepth = scalar(@{$cats});
 8530:         if (ref($cats->[$depth]) eq 'HASH') {
 8531:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 8532:                 my $numchildren = @{$cats->[$depth]{$parent}};
 8533:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8534:                 $text .= '<td><table class="LC_datatable">';
 8535:                 for (my $j=0; $j<$numchildren; $j++) {
 8536:                     $name = $cats->[$depth]{$parent}[$j];
 8537:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 8538:                     my $deeper = $depth+1;
 8539:                     my $checked = '';
 8540:                     if (ref($currcategories) eq 'ARRAY') {
 8541:                         if (@{$currcategories} > 0) {
 8542:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 8543:                                 $checked = ' checked="checked" ';
 8544:                             }
 8545:                         }
 8546:                     }
 8547:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 8548:                              '<input type="checkbox" name="usecategory" value="'.
 8549:                              $item.'"'.$checked.' />'.$name.'</label></span></td><td>';
 8550:                     if (ref($path) eq 'ARRAY') {
 8551:                         push(@{$path},$name);
 8552:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 8553:                         pop(@{$path});
 8554:                     }
 8555:                     $text .= '</td></tr>';
 8556:                 }
 8557:                 $text .= '</table></td>';
 8558:             }
 8559:         }
 8560:     }
 8561:     return $text;
 8562: }
 8563: 
 8564: ############################################################
 8565: ############################################################
 8566: 
 8567: 
 8568: sub commit_customrole {
 8569:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 8570:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 8571:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 8572:                          ($end?', ending '.localtime($end):'').': <b>'.
 8573:               &Apache::lonnet::assigncustomrole(
 8574:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 8575:                  '</b><br />';
 8576:     return $output;
 8577: }
 8578: 
 8579: sub commit_standardrole {
 8580:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 8581:     my ($output,$logmsg,$linefeed);
 8582:     if ($context eq 'auto') {
 8583:         $linefeed = "\n";
 8584:     } else {
 8585:         $linefeed = "<br />\n";
 8586:     }  
 8587:     if ($three eq 'st') {
 8588:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 8589:                                          $one,$two,$sec,$context);
 8590:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 8591:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 8592:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 8593:         } else {
 8594:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 8595:                ($start?', '.&mt('starting').' '.localtime($start):'').
 8596:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 8597:             if ($context eq 'auto') {
 8598:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 8599:             } else {
 8600:                $output .= '<b>'.$result.'</b>'.$linefeed.
 8601:                &mt('Add to classlist').': <b>ok</b>';
 8602:             }
 8603:             $output .= $linefeed;
 8604:         }
 8605:     } else {
 8606:         $output = &mt('Assigning').' '.$three.' in '.$url.
 8607:                ($start?', '.&mt('starting').' '.localtime($start):'').
 8608:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 8609:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 8610:         if ($context eq 'auto') {
 8611:             $output .= $result.$linefeed;
 8612:         } else {
 8613:             $output .= '<b>'.$result.'</b>'.$linefeed;
 8614:         }
 8615:     }
 8616:     return $output;
 8617: }
 8618: 
 8619: sub commit_studentrole {
 8620:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 8621:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 8622:     if ($context eq 'auto') {
 8623:         $linefeed = "\n";
 8624:     } else {
 8625:         $linefeed = '<br />'."\n";
 8626:     }
 8627:     if (defined($one) && defined($two)) {
 8628:         my $cid=$one.'_'.$two;
 8629:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 8630:         my $secchange = 0;
 8631:         my $expire_role_result;
 8632:         my $modify_section_result;
 8633:         if ($oldsec ne '-1') { 
 8634:             if ($oldsec ne $sec) {
 8635:                 $secchange = 1;
 8636:                 my $now = time;
 8637:                 my $uurl='/'.$cid;
 8638:                 $uurl=~s/\_/\//g;
 8639:                 if ($oldsec) {
 8640:                     $uurl.='/'.$oldsec;
 8641:                 }
 8642:                 $oldsecurl = $uurl;
 8643:                 $expire_role_result = 
 8644:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 8645:                 if ($env{'request.course.sec'} ne '') { 
 8646:                     if ($expire_role_result eq 'refused') {
 8647:                         my @roles = ('st');
 8648:                         my @statuses = ('previous');
 8649:                         my @roledoms = ($one);
 8650:                         my $withsec = 1;
 8651:                         my %roleshash = 
 8652:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 8653:                                               \@statuses,\@roles,\@roledoms,$withsec);
 8654:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 8655:                             my ($oldstart,$oldend) = 
 8656:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 8657:                             if ($oldend > 0 && $oldend <= $now) {
 8658:                                 $expire_role_result = 'ok';
 8659:                             }
 8660:                         }
 8661:                     }
 8662:                 }
 8663:                 $result = $expire_role_result;
 8664:             }
 8665:         }
 8666:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 8667:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 8668:             if ($modify_section_result =~ /^ok/) {
 8669:                 if ($secchange == 1) {
 8670:                     if ($sec eq '') {
 8671:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 8672:                     } else {
 8673:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 8674:                     }
 8675:                 } elsif ($oldsec eq '-1') {
 8676:                     if ($sec eq '') {
 8677:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 8678:                     } else {
 8679:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8680:                     }
 8681:                 } else {
 8682:                     if ($sec eq '') {
 8683:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 8684:                     } else {
 8685:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8686:                     }
 8687:                 }
 8688:             } else {
 8689:                 if ($secchange) {       
 8690:                     $$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;
 8691:                 } else {
 8692:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 8693:                 }
 8694:             }
 8695:             $result = $modify_section_result;
 8696:         } elsif ($secchange == 1) {
 8697:             if ($oldsec eq '') {
 8698:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 8699:             } else {
 8700:                 $$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;
 8701:             }
 8702:             if ($expire_role_result eq 'refused') {
 8703:                 my $newsecurl = '/'.$cid;
 8704:                 $newsecurl =~ s/\_/\//g;
 8705:                 if ($sec ne '') {
 8706:                     $newsecurl.='/'.$sec;
 8707:                 }
 8708:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 8709:                     if ($sec eq '') {
 8710:                         $$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;
 8711:                     } else {
 8712:                         $$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;
 8713:                     }
 8714:                 }
 8715:             }
 8716:         }
 8717:     } else {
 8718:         $$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;
 8719:         $result = "error: incomplete course id\n";
 8720:     }
 8721:     return $result;
 8722: }
 8723: 
 8724: ############################################################
 8725: ############################################################
 8726: 
 8727: sub check_clone {
 8728:     my ($args,$linefeed) = @_;
 8729:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 8730:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 8731:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 8732:     my $clonemsg;
 8733:     my $can_clone = 0;
 8734: 
 8735:     if ($clonehome eq 'no_host') {
 8736:         $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'});     
 8737:     } else {
 8738: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 8739: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 8740: 	    $can_clone = 1;
 8741: 	} else {
 8742: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 8743: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 8744: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 8745:             if (grep(/^\*$/,@cloners)) {
 8746:                 $can_clone = 1;
 8747:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 8748:                 $can_clone = 1;
 8749:             } else {
 8750: 	        my %roleshash =
 8751: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 8752: 					 $args->{'ccdomain'},
 8753:                                          'userroles',['active'],['cc'],
 8754: 					 [$args->{'clonedomain'}]);
 8755: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 8756: 		    $can_clone = 1;
 8757: 	        } else {
 8758:                     $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'});
 8759: 	        }
 8760: 	    }
 8761:         }
 8762:     }
 8763:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 8764: }
 8765: 
 8766: sub construct_course {
 8767:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 8768:     my $outcome;
 8769:     my $linefeed =  '<br />'."\n";
 8770:     if ($context eq 'auto') {
 8771:         $linefeed = "\n";
 8772:     }
 8773: 
 8774: #
 8775: # Are we cloning?
 8776: #
 8777:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 8778:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 8779: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 8780: 	if ($context ne 'auto') {
 8781:             if ($clonemsg ne '') {
 8782: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 8783:             }
 8784: 	}
 8785: 	$outcome .= $clonemsg.$linefeed;
 8786: 
 8787:         if (!$can_clone) {
 8788: 	    return (0,$outcome);
 8789: 	}
 8790:     }
 8791: 
 8792: #
 8793: # Open course
 8794: #
 8795:     my $crstype = lc($args->{'crstype'});
 8796:     my %cenv=();
 8797:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 8798:                                              $args->{'cdescr'},
 8799:                                              $args->{'curl'},
 8800:                                              $args->{'course_home'},
 8801:                                              $args->{'nonstandard'},
 8802:                                              $args->{'crscode'},
 8803:                                              $args->{'ccuname'}.':'.
 8804:                                              $args->{'ccdomain'},
 8805:                                              $args->{'crstype'});
 8806: 
 8807:     # Note: The testing routines depend on this being output; see 
 8808:     # Utils::Course. This needs to at least be output as a comment
 8809:     # if anyone ever decides to not show this, and Utils::Course::new
 8810:     # will need to be suitably modified.
 8811:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 8812: #
 8813: # Check if created correctly
 8814: #
 8815:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 8816:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 8817:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 8818: 
 8819: #
 8820: # Do the cloning
 8821: #   
 8822:     if ($can_clone && $cloneid) {
 8823: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 8824: 	if ($context ne 'auto') {
 8825: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 8826: 	}
 8827: 	$outcome .= $clonemsg.$linefeed;
 8828: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 8829: # Copy all files
 8830: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 8831: # Restore URL
 8832: 	$cenv{'url'}=$oldcenv{'url'};
 8833: # Restore title
 8834: 	$cenv{'description'}=$oldcenv{'description'};
 8835: # Mark as cloned
 8836: 	$cenv{'clonedfrom'}=$cloneid;
 8837: # Need to clone grading mode
 8838:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 8839:         $cenv{'grading'}=$newenv{'grading'};
 8840: # Do not clone these environment entries
 8841:         &Apache::lonnet::del('environment',
 8842:                   ['default_enrollment_start_date',
 8843:                    'default_enrollment_end_date',
 8844:                    'question.email',
 8845:                    'policy.email',
 8846:                    'comment.email',
 8847:                    'pch.users.denied',
 8848:                    'plc.users.denied'],
 8849:                    $$crsudom,$$crsunum);
 8850:     }
 8851: 
 8852: #
 8853: # Set environment (will override cloned, if existing)
 8854: #
 8855:     my @sections = ();
 8856:     my @xlists = ();
 8857:     if ($args->{'crstype'}) {
 8858:         $cenv{'type'}=$args->{'crstype'};
 8859:     }
 8860:     if ($args->{'crsid'}) {
 8861:         $cenv{'courseid'}=$args->{'crsid'};
 8862:     }
 8863:     if ($args->{'crscode'}) {
 8864:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 8865:     }
 8866:     if ($args->{'crsquota'} ne '') {
 8867:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 8868:     } else {
 8869:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 8870:     }
 8871:     if ($args->{'ccuname'}) {
 8872:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 8873:                                         ':'.$args->{'ccdomain'};
 8874:     } else {
 8875:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 8876:     }
 8877:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 8878:     if ($args->{'crssections'}) {
 8879:         $cenv{'internal.sectionnums'} = '';
 8880:         if ($args->{'crssections'} =~ m/,/) {
 8881:             @sections = split/,/,$args->{'crssections'};
 8882:         } else {
 8883:             $sections[0] = $args->{'crssections'};
 8884:         }
 8885:         if (@sections > 0) {
 8886:             foreach my $item (@sections) {
 8887:                 my ($sec,$gp) = split/:/,$item;
 8888:                 my $class = $args->{'crscode'}.$sec;
 8889:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 8890:                 $cenv{'internal.sectionnums'} .= $item.',';
 8891:                 unless ($addcheck eq 'ok') {
 8892:                     push @badclasses, $class;
 8893:                 }
 8894:             }
 8895:             $cenv{'internal.sectionnums'} =~ s/,$//;
 8896:         }
 8897:     }
 8898: # do not hide course coordinator from staff listing, 
 8899: # even if privileged
 8900:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 8901: # add crosslistings
 8902:     if ($args->{'crsxlist'}) {
 8903:         $cenv{'internal.crosslistings'}='';
 8904:         if ($args->{'crsxlist'} =~ m/,/) {
 8905:             @xlists = split/,/,$args->{'crsxlist'};
 8906:         } else {
 8907:             $xlists[0] = $args->{'crsxlist'};
 8908:         }
 8909:         if (@xlists > 0) {
 8910:             foreach my $item (@xlists) {
 8911:                 my ($xl,$gp) = split/:/,$item;
 8912:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 8913:                 $cenv{'internal.crosslistings'} .= $item.',';
 8914:                 unless ($addcheck eq 'ok') {
 8915:                     push @badclasses, $xl;
 8916:                 }
 8917:             }
 8918:             $cenv{'internal.crosslistings'} =~ s/,$//;
 8919:         }
 8920:     }
 8921:     if ($args->{'autoadds'}) {
 8922:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 8923:     }
 8924:     if ($args->{'autodrops'}) {
 8925:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 8926:     }
 8927: # check for notification of enrollment changes
 8928:     my @notified = ();
 8929:     if ($args->{'notify_owner'}) {
 8930:         if ($args->{'ccuname'} ne '') {
 8931:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 8932:         }
 8933:     }
 8934:     if ($args->{'notify_dc'}) {
 8935:         if ($uname ne '') { 
 8936:             push(@notified,$uname.':'.$udom);
 8937:         }
 8938:     }
 8939:     if (@notified > 0) {
 8940:         my $notifylist;
 8941:         if (@notified > 1) {
 8942:             $notifylist = join(',',@notified);
 8943:         } else {
 8944:             $notifylist = $notified[0];
 8945:         }
 8946:         $cenv{'internal.notifylist'} = $notifylist;
 8947:     }
 8948:     if (@badclasses > 0) {
 8949:         my %lt=&Apache::lonlocal::texthash(
 8950:                 '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',
 8951:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 8952:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 8953:         );
 8954:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 8955:                            ' ('.$lt{'adby'}.')';
 8956:         if ($context eq 'auto') {
 8957:             $outcome .= $badclass_msg.$linefeed;
 8958:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 8959:             foreach my $item (@badclasses) {
 8960:                 if ($context eq 'auto') {
 8961:                     $outcome .= " - $item\n";
 8962:                 } else {
 8963:                     $outcome .= "<li>$item</li>\n";
 8964:                 }
 8965:             }
 8966:             if ($context eq 'auto') {
 8967:                 $outcome .= $linefeed;
 8968:             } else {
 8969:                 $outcome .= "</ul><br /><br /></div>\n";
 8970:             }
 8971:         } 
 8972:     }
 8973:     if ($args->{'no_end_date'}) {
 8974:         $args->{'endaccess'} = 0;
 8975:     }
 8976:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 8977:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 8978:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 8979:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 8980:     if ($args->{'showphotos'}) {
 8981:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 8982:     }
 8983:     $cenv{'internal.authtype'} = $args->{'authtype'};
 8984:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 8985:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 8986:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 8987:             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'); 
 8988:             if ($context eq 'auto') {
 8989:                 $outcome .= $krb_msg;
 8990:             } else {
 8991:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 8992:             }
 8993:             $outcome .= $linefeed;
 8994:         }
 8995:     }
 8996:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 8997:        if ($args->{'setpolicy'}) {
 8998:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 8999:        }
 9000:        if ($args->{'setcontent'}) {
 9001:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9002:        }
 9003:     }
 9004:     if ($args->{'reshome'}) {
 9005: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9006: 	$cenv{'reshome'}=~s/\/+$/\//;
 9007:     }
 9008: #
 9009: # course has keyed access
 9010: #
 9011:     if ($args->{'setkeys'}) {
 9012:        $cenv{'keyaccess'}='yes';
 9013:     }
 9014: # if specified, key authority is not course, but user
 9015: # only active if keyaccess is yes
 9016:     if ($args->{'keyauth'}) {
 9017: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9018: 	$user = &LONCAPA::clean_username($user);
 9019: 	$domain = &LONCAPA::clean_username($domain);
 9020: 	if ($user ne '' && $domain ne '') {
 9021: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9022: 	}
 9023:     }
 9024: 
 9025:     if ($args->{'disresdis'}) {
 9026:         $cenv{'pch.roles.denied'}='st';
 9027:     }
 9028:     if ($args->{'disablechat'}) {
 9029:         $cenv{'plc.roles.denied'}='st';
 9030:     }
 9031: 
 9032:     # Record we've not yet viewed the Course Initialization Helper for this 
 9033:     # course
 9034:     $cenv{'course.helper.not.run'} = 1;
 9035:     #
 9036:     # Use new Randomseed
 9037:     #
 9038:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9039:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9040:     #
 9041:     # The encryption code and receipt prefix for this course
 9042:     #
 9043:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9044:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9045:     #
 9046:     # By default, use standard grading
 9047:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9048: 
 9049:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9050:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9051: #
 9052: # Open all assignments
 9053: #
 9054:     if ($args->{'openall'}) {
 9055:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9056:        my %storecontent = ($storeunder         => time,
 9057:                            $storeunder.'.type' => 'date_start');
 9058:        
 9059:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9060:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9061:    }
 9062: #
 9063: # Set first page
 9064: #
 9065:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9066: 	    || ($cloneid)) {
 9067: 	use LONCAPA::map;
 9068: 	$outcome .= &mt('Setting first resource').': ';
 9069: 
 9070: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9071:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9072: 
 9073:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9074:         my $title; my $url;
 9075:         if ($args->{'firstres'} eq 'syl') {
 9076: 	    $title='Syllabus';
 9077:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9078:         } else {
 9079:             $title='Navigate Contents';
 9080:             $url='/adm/navmaps';
 9081:         }
 9082: 
 9083:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9084: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9085: 
 9086: 	if ($errtext) { $fatal=2; }
 9087:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9088:     }
 9089: 
 9090:     return (1,$outcome);
 9091: }
 9092: 
 9093: ############################################################
 9094: ############################################################
 9095: 
 9096: sub course_type {
 9097:     my ($cid) = @_;
 9098:     if (!defined($cid)) {
 9099:         $cid = $env{'request.course.id'};
 9100:     }
 9101:     if (defined($env{'course.'.$cid.'.type'})) {
 9102:         return $env{'course.'.$cid.'.type'};
 9103:     } else {
 9104:         return 'Course';
 9105:     }
 9106: }
 9107: 
 9108: sub group_term {
 9109:     my $crstype = &course_type();
 9110:     my %names = (
 9111:                   'Course' => 'group',
 9112:                   'Group' => 'team',
 9113:                 );
 9114:     return $names{$crstype};
 9115: }
 9116: 
 9117: sub icon {
 9118:     my ($file)=@_;
 9119:     my $curfext = lc((split(/\./,$file))[-1]);
 9120:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9121:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9122:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9123: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9124: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9125: 	            $curfext.".gif") {
 9126: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9127: 		$curfext.".gif";
 9128: 	}
 9129:     }
 9130:     return &lonhttpdurl($iconname);
 9131: } 
 9132: 
 9133: sub lonhttpd_port {
 9134:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 9135:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 9136:     # IE doesn't like a secure page getting images from a non-secure
 9137:     # port (when logging we haven't parsed the browser type so default
 9138:     # back to secure
 9139:     if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
 9140: 	&& $ENV{'SERVER_PORT'} == 443) {
 9141: 	return 443;
 9142:     }
 9143:     return $lonhttpd_port;
 9144: 
 9145: }
 9146: 
 9147: sub lonhttpdurl {
 9148:     my ($url)=@_;
 9149: 
 9150:     my $lonhttpd_port = &lonhttpd_port();
 9151:     if ($lonhttpd_port == 443) {
 9152: 	return 'https://'.$ENV{'SERVER_NAME'}.$url;
 9153:     }
 9154:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 9155: }
 9156: 
 9157: sub connection_aborted {
 9158:     my ($r)=@_;
 9159:     $r->print(" ");$r->rflush();
 9160:     my $c = $r->connection;
 9161:     return $c->aborted();
 9162: }
 9163: 
 9164: #    Escapes strings that may have embedded 's that will be put into
 9165: #    strings as 'strings'.
 9166: sub escape_single {
 9167:     my ($input) = @_;
 9168:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9169:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9170:     return $input;
 9171: }
 9172: 
 9173: #  Same as escape_single, but escape's "'s  This 
 9174: #  can be used for  "strings"
 9175: sub escape_double {
 9176:     my ($input) = @_;
 9177:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9178:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9179:     return $input;
 9180: }
 9181:  
 9182: #   Escapes the last element of a full URL.
 9183: sub escape_url {
 9184:     my ($url)   = @_;
 9185:     my @urlslices = split(/\//, $url,-1);
 9186:     my $lastitem = &escape(pop(@urlslices));
 9187:     return join('/',@urlslices).'/'.$lastitem;
 9188: }
 9189: 
 9190: # -------------------------------------------------------- Initliaze user login
 9191: sub init_user_environment {
 9192:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9193:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9194: 
 9195:     my $public=($username eq 'public' && $domain eq 'public');
 9196: 
 9197: # See if old ID present, if so, remove
 9198: 
 9199:     my ($filename,$cookie,$userroles);
 9200:     my $now=time;
 9201: 
 9202:     if ($public) {
 9203: 	my $max_public=100;
 9204: 	my $oldest;
 9205: 	my $oldest_time=0;
 9206: 	for(my $next=1;$next<=$max_public;$next++) {
 9207: 	    if (-e $lonids."/publicuser_$next.id") {
 9208: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9209: 		if ($mtime<$oldest_time || !$oldest_time) {
 9210: 		    $oldest_time=$mtime;
 9211: 		    $oldest=$next;
 9212: 		}
 9213: 	    } else {
 9214: 		$cookie="publicuser_$next";
 9215: 		last;
 9216: 	    }
 9217: 	}
 9218: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9219:     } else {
 9220: 	# if this isn't a robot, kill any existing non-robot sessions
 9221: 	if (!$args->{'robot'}) {
 9222: 	    opendir(DIR,$lonids);
 9223: 	    while ($filename=readdir(DIR)) {
 9224: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9225: 		    unlink($lonids.'/'.$filename);
 9226: 		}
 9227: 	    }
 9228: 	    closedir(DIR);
 9229: 	}
 9230: # Give them a new cookie
 9231: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9232: 		                   : $now);
 9233: 	$cookie="$username\_$id\_$domain\_$authhost";
 9234:     
 9235: # Initialize roles
 9236: 
 9237: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9238:     }
 9239: # ------------------------------------ Check browser type and MathML capability
 9240: 
 9241:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9242:         $clientunicode,$clientos) = &decode_user_agent($r);
 9243: 
 9244: # -------------------------------------- Any accessibility options to remember?
 9245:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9246: 	foreach my $option ('imagesuppress','appletsuppress',
 9247: 			    'embedsuppress','fontenhance','blackwhite') {
 9248: 	    if ($form->{$option} eq 'true') {
 9249: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9250: 				     $domain,$username);
 9251: 	    } else {
 9252: 		&Apache::lonnet::del('environment',[$option],
 9253: 				     $domain,$username);
 9254: 	    }
 9255: 	}
 9256:     }
 9257: # ------------------------------------------------------------- Get environment
 9258: 
 9259:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9260:     my ($tmp) = keys(%userenv);
 9261:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9262: 	# default remote control to off
 9263: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9264:     } else {
 9265: 	undef(%userenv);
 9266:     }
 9267:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9268: 	$form->{'interface'}=$userenv{'interface'};
 9269:     }
 9270:     $env{'environment.remote'}=$userenv{'remote'};
 9271:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9272: 
 9273: # --------------- Do not trust query string to be put directly into environment
 9274:     foreach my $option ('imagesuppress','appletsuppress',
 9275: 			'embedsuppress','fontenhance','blackwhite',
 9276: 			'interface','localpath','localres') {
 9277: 	$form->{$option}=~s/[\n\r\=]//gs;
 9278:     }
 9279: # --------------------------------------------------------- Write first profile
 9280: 
 9281:     {
 9282: 	my %initial_env = 
 9283: 	    ("user.name"          => $username,
 9284: 	     "user.domain"        => $domain,
 9285: 	     "user.home"          => $authhost,
 9286: 	     "browser.type"       => $clientbrowser,
 9287: 	     "browser.version"    => $clientversion,
 9288: 	     "browser.mathml"     => $clientmathml,
 9289: 	     "browser.unicode"    => $clientunicode,
 9290: 	     "browser.os"         => $clientos,
 9291: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9292: 	     "request.course.fn"  => '',
 9293: 	     "request.course.uri" => '',
 9294: 	     "request.course.sec" => '',
 9295: 	     "request.role"       => 'cm',
 9296: 	     "request.role.adv"   => $env{'user.adv'},
 9297: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9298: 
 9299:         if ($form->{'localpath'}) {
 9300: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9301: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9302:         }
 9303: 	
 9304: 	if ($public) {
 9305: 	    $initial_env{"environment.remote"} = "off";
 9306: 	}
 9307: 	if ($form->{'interface'}) {
 9308: 	    $form->{'interface'}=~s/\W//gs;
 9309: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9310: 	    $env{'browser.interface'}=$form->{'interface'};
 9311: 	    foreach my $option ('imagesuppress','appletsuppress',
 9312: 				'embedsuppress','fontenhance','blackwhite') {
 9313: 		if (($form->{$option} eq 'true') ||
 9314: 		    ($userenv{$option} eq 'on')) {
 9315: 		    $initial_env{"browser.$option"} = "on";
 9316: 		}
 9317: 	    }
 9318: 	}
 9319: 
 9320: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9321: 	
 9322: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9323: 		 &GDBM_WRCREAT(),0640)) {
 9324: 	    &_add_to_env(\%disk_env,\%initial_env);
 9325: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9326: 	    &_add_to_env(\%disk_env,$userroles);
 9327: 	    if (ref($args->{'extra_env'})) {
 9328: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9329: 	    }
 9330: 	    untie(%disk_env);
 9331: 	} else {
 9332: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 9333: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 9334: 	    return 'error: '.$!;
 9335: 	}
 9336:     }
 9337:     $env{'request.role'}='cm';
 9338:     $env{'request.role.adv'}=$env{'user.adv'};
 9339:     $env{'browser.type'}=$clientbrowser;
 9340: 
 9341:     return $cookie;
 9342: 
 9343: }
 9344: 
 9345: sub _add_to_env {
 9346:     my ($idf,$env_data,$prefix) = @_;
 9347:     while (my ($key,$value) = each(%$env_data)) {
 9348: 	$idf->{$prefix.$key} = $value;
 9349: 	$env{$prefix.$key}   = $value;
 9350:     }
 9351: }
 9352: 
 9353: 
 9354: =pod
 9355: 
 9356: =back
 9357: 
 9358: =cut
 9359: 
 9360: 1;
 9361: __END__;
 9362: 

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