File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.679.2.4: download - view: text, annotated - select for diffs
Fri Sep 19 23:03:20 2008 UTC (15 years, 8 months ago) by raeburn
Branches: version_2_7_X
Backport 1.686.

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

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