File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.672: download - view: text, annotated - select for diffs
Wed Jul 23 10:07:25 2008 UTC (15 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_6_99_1, HEAD
- Domain Coordinator access to Domain Coordination manual.

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

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