File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.948.2.33: download - view: text, annotated - select for diffs
Tue Nov 8 02:27:47 2011 UTC (12 years, 6 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_1, loncapaMITrelate_1
- Backport 1.1026 (part).

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.948.2.33 2011/11/08 02:27:47 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 Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410: // <![CDATA[
  411:     var stdeditbrowser;
  412:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  413:         var url = '/adm/pickstudent?';
  414:         var filter;
  415: 	if (!ignorefilter) {
  416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  417: 	}
  418:         if (filter != null) {
  419:            if (filter != '') {
  420:                url += 'filter='+filter+'&';
  421: 	   }
  422:         }
  423:         url += 'form=' + formname + '&unameelement='+uname+
  424:                                     '&udomelement='+udom+
  425:                                     '&clicker='+clicker;
  426: 	if (roleflag) { url+="&roles=1"; }
  427:         if (courseadvonly) { url+="&courseadvonly=1"; }
  428:         var title = 'Student_Browser';
  429:         var options = 'scrollbars=1,resizable=1,menubar=0';
  430:         options += ',width=700,height=600';
  431:         stdeditbrowser = open(url,title,options,'1');
  432:         stdeditbrowser.focus();
  433:     }
  434: // ]]>
  435: </script>
  436: ENDSTDBRW
  437: }
  438: 
  439: sub selectstudent_link {
  440:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  441:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  442:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  443:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  444:    if ($env{'request.course.id'}) {  
  445:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  446: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  447: 					'/'.$env{'request.course.sec'})) {
  448: 	   return '';
  449:        }
  450:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  451:        if ($courseadvonly)  {
  452:            $callargs .= ",'',1,1";
  453:        }
  454:        return '<span class="LC_nobreak">'.
  455:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  456:               &mt('Select User').'</a></span>';
  457:    }
  458:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  459:        $callargs .= ",'',1";
  460:        return '<span class="LC_nobreak">'.
  461:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  462:               &mt('Select User').'</a></span>';
  463:    }
  464:    return '';
  465: }
  466: 
  467: sub authorbrowser_javascript {
  468:     return <<"ENDAUTHORBRW";
  469: <script type="text/javascript" language="JavaScript">
  470: // <![CDATA[
  471: var stdeditbrowser;
  472: 
  473: function openauthorbrowser(formname,udom) {
  474:     var url = '/adm/pickauthor?';
  475:     url += 'form='+formname+'&roledom='+udom;
  476:     var title = 'Author_Browser';
  477:     var options = 'scrollbars=1,resizable=1,menubar=0';
  478:     options += ',width=700,height=600';
  479:     stdeditbrowser = open(url,title,options,'1');
  480:     stdeditbrowser.focus();
  481: }
  482: 
  483: // ]]>
  484: </script>
  485: ENDAUTHORBRW
  486: }
  487: 
  488: sub coursebrowser_javascript {
  489:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  490:     my $wintitle = 'Course_Browser';
  491:     if ($crstype eq 'Community') {
  492:         $wintitle = 'Community_Browser';
  493:     }
  494:     my $id_functions = &javascript_index_functions();
  495:     my $output = '
  496: <script type="text/javascript" language="JavaScript">
  497: // <![CDATA[
  498:     var stdeditbrowser;'."\n";
  499: 
  500:     $output .= <<"ENDSTDBRW";
  501:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  502:         var url = '/adm/pickcourse?';
  503:         var formid = getFormIdByName(formname);
  504:         var domainfilter = getDomainFromSelectbox(formname,udom);
  505:         if (domainfilter != null) {
  506:            if (domainfilter != '') {
  507:                url += 'domainfilter='+domainfilter+'&';
  508: 	   }
  509:         }
  510:         url += 'form=' + formname + '&cnumelement='+uname+
  511: 	                            '&cdomelement='+udom+
  512:                                     '&cnameelement='+desc;
  513:         if (extra_element !=null && extra_element != '') {
  514:             if (formname == 'rolechoice' || formname == 'studentform') {
  515:                 url += '&roleelement='+extra_element;
  516:                 if (domainfilter == null || domainfilter == '') {
  517:                     url += '&domainfilter='+extra_element;
  518:                 }
  519:             }
  520:             else {
  521:                 if (formname == 'portform') {
  522:                     url += '&setroles='+extra_element;
  523:                 } else {
  524:                     if (formname == 'rules') {
  525:                         url += '&fixeddom='+extra_element; 
  526:                     }
  527:                 }
  528:             }     
  529:         }
  530:         if (type != null && type != '') {
  531:             url += '&type='+type;
  532:         }
  533:         if (type_elem != null && type_elem != '') {
  534:             url += '&typeelement='+type_elem;
  535:         }
  536:         if (formname == 'ccrs') {
  537:             var ownername = document.forms[formid].ccuname.value;
  538:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  539:             url += '&cloner='+ownername+':'+ownerdom;
  540:         }
  541:         if (multflag !=null && multflag != '') {
  542:             url += '&multiple='+multflag;
  543:         }
  544:         var title = '$wintitle';
  545:         var options = 'scrollbars=1,resizable=1,menubar=0';
  546:         options += ',width=700,height=600';
  547:         stdeditbrowser = open(url,title,options,'1');
  548:         stdeditbrowser.focus();
  549:     }
  550: $id_functions
  551: ENDSTDBRW
  552:     if (($sec_element ne '') || ($role_element ne '')) {
  553:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  554:     }
  555:     $output .= '
  556: // ]]>
  557: </script>';
  558:     return $output;
  559: }
  560: 
  561: sub javascript_index_functions {
  562:     return <<"ENDJS";
  563: 
  564: function getFormIdByName(formname) {
  565:     for (var i=0;i<document.forms.length;i++) {
  566:         if (document.forms[i].name == formname) {
  567:             return i;
  568:         }
  569:     }
  570:     return -1;
  571: }
  572: 
  573: function getIndexByName(formid,item) {
  574:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  575:         if (document.forms[formid].elements[i].name == item) {
  576:             return i;
  577:         }
  578:     }
  579:     return -1;
  580: }
  581: 
  582: function getDomainFromSelectbox(formname,udom) {
  583:     var userdom;
  584:     var formid = getFormIdByName(formname);
  585:     if (formid > -1) {
  586:         var domid = getIndexByName(formid,udom);
  587:         if (domid > -1) {
  588:             if (document.forms[formid].elements[domid].type == 'select-one') {
  589:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  590:             }
  591:             if (document.forms[formid].elements[domid].type == 'hidden') {
  592:                 userdom=document.forms[formid].elements[domid].value;
  593:             }
  594:         }
  595:     }
  596:     return userdom;
  597: }
  598: 
  599: ENDJS
  600: 
  601: }
  602: 
  603: sub javascript_array_indexof {
  604:     return <<ENDJS;
  605: <script type="text/javascript" language="JavaScript">
  606: // <![CDATA[
  607: 
  608: if (!Array.prototype.indexOf) {
  609:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  610:         "use strict";
  611:         if (this === void 0 || this === null) {
  612:             throw new TypeError();
  613:         }
  614:         var t = Object(this);
  615:         var len = t.length >>> 0;
  616:         if (len === 0) {
  617:             return -1;
  618:         }
  619:         var n = 0;
  620:         if (arguments.length > 0) {
  621:             n = Number(arguments[1]);
  622:             if (n !== n) { // shortcut for verifying if it's NaN
  623:                 n = 0;
  624:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  625:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  626:             }
  627:         }
  628:         if (n >= len) {
  629:             return -1;
  630:         }
  631:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  632:         for (; k < len; k++) {
  633:             if (k in t && t[k] === searchElement) {
  634:                 return k;
  635:             }
  636:         }
  637:         return -1;
  638:     }
  639: }
  640: 
  641: // ]]>
  642: </script>
  643: 
  644: ENDJS
  645: 
  646: }
  647: 
  648: sub userbrowser_javascript {
  649:     my $id_functions = &javascript_index_functions();
  650:     return <<"ENDUSERBRW";
  651: 
  652: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  653:     var url = '/adm/pickuser?';
  654:     var userdom = getDomainFromSelectbox(formname,udom);
  655:     if (userdom != null) {
  656:        if (userdom != '') {
  657:            url += 'srchdom='+userdom+'&';
  658:        }
  659:     }
  660:     url += 'form=' + formname + '&unameelement='+uname+
  661:                                 '&udomelement='+udom+
  662:                                 '&ulastelement='+ulast+
  663:                                 '&ufirstelement='+ufirst+
  664:                                 '&uemailelement='+uemail+
  665:                                 '&hideudomelement='+hideudom+
  666:                                 '&coursedom='+crsdom;
  667:     if ((caller != null) && (caller != undefined)) {
  668:         url += '&caller='+caller;
  669:     }
  670:     var title = 'User_Browser';
  671:     var options = 'scrollbars=1,resizable=1,menubar=0';
  672:     options += ',width=700,height=600';
  673:     var stdeditbrowser = open(url,title,options,'1');
  674:     stdeditbrowser.focus();
  675: }
  676: 
  677: function fix_domain (formname,udom,origdom,uname) {
  678:     var formid = getFormIdByName(formname);
  679:     if (formid > -1) {
  680:         var unameid = getIndexByName(formid,uname);
  681:         var domid = getIndexByName(formid,udom);
  682:         var hidedomid = getIndexByName(formid,origdom);
  683:         if (hidedomid > -1) {
  684:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  685:             var unameval = document.forms[formid].elements[unameid].value;
  686:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  687:                 if (domid > -1) {
  688:                     var slct = document.forms[formid].elements[domid];
  689:                     if (slct.type == 'select-one') {
  690:                         var i;
  691:                         for (i=0;i<slct.length;i++) {
  692:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  693:                         }
  694:                     }
  695:                     if (slct.type == 'hidden') {
  696:                         slct.value = fixeddom;
  697:                     }
  698:                 }
  699:             }
  700:         }
  701:     }
  702:     return;
  703: }
  704: 
  705: $id_functions
  706: ENDUSERBRW
  707: }
  708: 
  709: sub setsec_javascript {
  710:     my ($sec_element,$formname,$role_element) = @_;
  711:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  712:         $communityrolestr);
  713:     if ($role_element ne '') {
  714:         my @allroles = ('st','ta','ep','in','ad');
  715:         foreach my $crstype ('Course','Community') {
  716:             if ($crstype eq 'Community') {
  717:                 foreach my $role (@allroles) {
  718:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  719:                 }
  720:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  721:             } else {
  722:                 foreach my $role (@allroles) {
  723:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  724:                 }
  725:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  726:             }
  727:         }
  728:         $rolestr = '"'.join('","',@allroles).'"';
  729:         $courserolestr = '"'.join('","',@courserolenames).'"';
  730:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  731:     }
  732:     my $setsections = qq|
  733: function setSect(sectionlist) {
  734:     var sectionsArray = new Array();
  735:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  736:         sectionsArray = sectionlist.split(",");
  737:     }
  738:     var numSections = sectionsArray.length;
  739:     document.$formname.$sec_element.length = 0;
  740:     if (numSections == 0) {
  741:         document.$formname.$sec_element.multiple=false;
  742:         document.$formname.$sec_element.size=1;
  743:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  744:     } else {
  745:         if (numSections == 1) {
  746:             document.$formname.$sec_element.multiple=false;
  747:             document.$formname.$sec_element.size=1;
  748:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  749:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  750:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  751:         } else {
  752:             for (var i=0; i<numSections; i++) {
  753:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  754:             }
  755:             document.$formname.$sec_element.multiple=true
  756:             if (numSections < 3) {
  757:                 document.$formname.$sec_element.size=numSections;
  758:             } else {
  759:                 document.$formname.$sec_element.size=3;
  760:             }
  761:             document.$formname.$sec_element.options[0].selected = false
  762:         }
  763:     }
  764: }
  765: 
  766: function setRole(crstype) {
  767: |;
  768:     if ($role_element eq '') {
  769:         $setsections .= '    return;
  770: }
  771: ';
  772:     } else {
  773:         $setsections .= qq|
  774:     var elementLength = document.$formname.$role_element.length;
  775:     var allroles = Array($rolestr);
  776:     var courserolenames = Array($courserolestr);
  777:     var communityrolenames = Array($communityrolestr);
  778:     if (elementLength != undefined) {
  779:         if (document.$formname.$role_element.options[5].value == 'cc') {
  780:             if (crstype == 'Course') {
  781:                 return;
  782:             } else {
  783:                 allroles[5] = 'co';
  784:                 for (var i=0; i<6; i++) {
  785:                     document.$formname.$role_element.options[i].value = allroles[i];
  786:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  787:                 }
  788:             }
  789:         } else {
  790:             if (crstype == 'Community') {
  791:                 return;
  792:             } else {
  793:                 allroles[5] = 'cc';
  794:                 for (var i=0; i<6; i++) {
  795:                     document.$formname.$role_element.options[i].value = allroles[i];
  796:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  797:                 }
  798:             }
  799:         }
  800:     }
  801:     return;
  802: }
  803: |;
  804:     }
  805:     return $setsections;
  806: }
  807: 
  808: sub selectcourse_link {
  809:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  810:        $typeelement) = @_;
  811:    my $type = $selecttype;
  812:    my $linktext = &mt('Select Course');
  813:    if ($selecttype eq 'Community') {
  814:        $linktext = &mt('Select Community');
  815:    } elsif ($selecttype eq 'Course/Community') {
  816:        $linktext = &mt('Select Course/Community');
  817:        $type = '';
  818:    } elsif ($selecttype eq 'Select') {
  819:        $linktext = &mt('Select');
  820:        $type = '';
  821:    }
  822:    return '<span class="LC_nobreak">'
  823:          ."<a href='"
  824:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  825:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  826:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  827:          ."'>".$linktext.'</a>'
  828:          .'</span>';
  829: }
  830: 
  831: sub selectauthor_link {
  832:    my ($form,$udom)=@_;
  833:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  834:           &mt('Select Author').'</a>';
  835: }
  836: 
  837: sub selectuser_link {
  838:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  839:         $coursedom,$linktext,$caller) = @_;
  840:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  841:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  842:            ');">'.$linktext.'</a>';
  843: }
  844: 
  845: sub check_uncheck_jscript {
  846:     my $jscript = <<"ENDSCRT";
  847: function checkAll(field) {
  848:     if (field.length > 0) {
  849:         for (i = 0; i < field.length; i++) {
  850:             field[i].checked = true ;
  851:         }
  852:     } else {
  853:         field.checked = true
  854:     }
  855: }
  856:  
  857: function uncheckAll(field) {
  858:     if (field.length > 0) {
  859:         for (i = 0; i < field.length; i++) {
  860:             field[i].checked = false ;
  861:         }
  862:     } else {
  863:         field.checked = false ;
  864:     }
  865: }
  866: ENDSCRT
  867:     return $jscript;
  868: }
  869: 
  870: sub select_timezone {
  871:    my ($name,$selected,$onchange,$includeempty)=@_;
  872:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  873:    if ($includeempty) {
  874:        $output .= '<option value=""';
  875:        if (($selected eq '') || ($selected eq 'local')) {
  876:            $output .= ' selected="selected" ';
  877:        }
  878:        $output .= '> </option>';
  879:    }
  880:    my @timezones = DateTime::TimeZone->all_names;
  881:    foreach my $tzone (@timezones) {
  882:        $output.= '<option value="'.$tzone.'"';
  883:        if ($tzone eq $selected) {
  884:            $output.=' selected="selected"';
  885:        }
  886:        $output.=">$tzone</option>\n";
  887:    }
  888:    $output.="</select>";
  889:    return $output;
  890: }
  891: 
  892: sub select_datelocale {
  893:     my ($name,$selected,$onchange,$includeempty)=@_;
  894:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  895:     if ($includeempty) {
  896:         $output .= '<option value=""';
  897:         if ($selected eq '') {
  898:             $output .= ' selected="selected" ';
  899:         }
  900:         $output .= '> </option>';
  901:     }
  902:     my (@possibles,%locale_names);
  903:     my @locales = DateTime::Locale::Catalog::Locales;
  904:     foreach my $locale (@locales) {
  905:         if (ref($locale) eq 'HASH') {
  906:             my $id = $locale->{'id'};
  907:             if ($id ne '') {
  908:                 my $en_terr = $locale->{'en_territory'};
  909:                 my $native_terr = $locale->{'native_territory'};
  910:                 my @languages = &Apache::lonlocal::preferred_languages();
  911:                 if (grep(/^en$/,@languages) || !@languages) {
  912:                     if ($en_terr ne '') {
  913:                         $locale_names{$id} = '('.$en_terr.')';
  914:                     } elsif ($native_terr ne '') {
  915:                         $locale_names{$id} = $native_terr;
  916:                     }
  917:                 } else {
  918:                     if ($native_terr ne '') {
  919:                         $locale_names{$id} = $native_terr.' ';
  920:                     } elsif ($en_terr ne '') {
  921:                         $locale_names{$id} = '('.$en_terr.')';
  922:                     }
  923:                 }
  924:                 push (@possibles,$id);
  925:             }
  926:         }
  927:     }
  928:     foreach my $item (sort(@possibles)) {
  929:         $output.= '<option value="'.$item.'"';
  930:         if ($item eq $selected) {
  931:             $output.=' selected="selected"';
  932:         }
  933:         $output.=">$item";
  934:         if ($locale_names{$item} ne '') {
  935:             $output.="  $locale_names{$item}</option>\n";
  936:         }
  937:         $output.="</option>\n";
  938:     }
  939:     $output.="</select>";
  940:     return $output;
  941: }
  942: 
  943: sub select_language {
  944:     my ($name,$selected,$includeempty) = @_;
  945:     my %langchoices;
  946:     if ($includeempty) {
  947:         %langchoices = ('' => 'No language preference');
  948:     }
  949:     foreach my $id (&languageids()) {
  950:         my $code = &supportedlanguagecode($id);
  951:         if ($code) {
  952:             $langchoices{$code} = &plainlanguagedescription($id);
  953:         }
  954:     }
  955:     return &select_form($selected,$name,\%langchoices);
  956: }
  957: 
  958: =pod
  959: 
  960: =item * &linked_select_forms(...)
  961: 
  962: linked_select_forms returns a string containing a <script></script> block
  963: and html for two <select> menus.  The select menus will be linked in that
  964: changing the value of the first menu will result in new values being placed
  965: in the second menu.  The values in the select menu will appear in alphabetical
  966: order unless a defined order is provided.
  967: 
  968: linked_select_forms takes the following ordered inputs:
  969: 
  970: =over 4
  971: 
  972: =item * $formname, the name of the <form> tag
  973: 
  974: =item * $middletext, the text which appears between the <select> tags
  975: 
  976: =item * $firstdefault, the default value for the first menu
  977: 
  978: =item * $firstselectname, the name of the first <select> tag
  979: 
  980: =item * $secondselectname, the name of the second <select> tag
  981: 
  982: =item * $hashref, a reference to a hash containing the data for the menus.
  983: 
  984: =item * $menuorder, the order of values in the first menu
  985: 
  986: =back 
  987: 
  988: Below is an example of such a hash.  Only the 'text', 'default', and 
  989: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  990: values for the first select menu.  The text that coincides with the 
  991: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  992: and text for the second menu are given in the hash pointed to by 
  993: $menu{$choice1}->{'select2'}.  
  994: 
  995:  my %menu = ( A1 => { text =>"Choice A1" ,
  996:                        default => "B3",
  997:                        select2 => { 
  998:                            B1 => "Choice B1",
  999:                            B2 => "Choice B2",
 1000:                            B3 => "Choice B3",
 1001:                            B4 => "Choice B4"
 1002:                            },
 1003:                        order => ['B4','B3','B1','B2'],
 1004:                    },
 1005:                A2 => { text =>"Choice A2" ,
 1006:                        default => "C2",
 1007:                        select2 => { 
 1008:                            C1 => "Choice C1",
 1009:                            C2 => "Choice C2",
 1010:                            C3 => "Choice C3"
 1011:                            },
 1012:                        order => ['C2','C1','C3'],
 1013:                    },
 1014:                A3 => { text =>"Choice A3" ,
 1015:                        default => "D6",
 1016:                        select2 => { 
 1017:                            D1 => "Choice D1",
 1018:                            D2 => "Choice D2",
 1019:                            D3 => "Choice D3",
 1020:                            D4 => "Choice D4",
 1021:                            D5 => "Choice D5",
 1022:                            D6 => "Choice D6",
 1023:                            D7 => "Choice D7"
 1024:                            },
 1025:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1026:                    }
 1027:                );
 1028: 
 1029: =cut
 1030: 
 1031: sub linked_select_forms {
 1032:     my ($formname,
 1033:         $middletext,
 1034:         $firstdefault,
 1035:         $firstselectname,
 1036:         $secondselectname, 
 1037:         $hashref,
 1038:         $menuorder,
 1039:         ) = @_;
 1040:     my $second = "document.$formname.$secondselectname";
 1041:     my $first = "document.$formname.$firstselectname";
 1042:     # output the javascript to do the changing
 1043:     my $result = '';
 1044:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1045:     $result.="// <![CDATA[\n";
 1046:     $result.="var select2data = new Object();\n";
 1047:     $" = '","';
 1048:     my $debug = '';
 1049:     foreach my $s1 (sort(keys(%$hashref))) {
 1050:         $result.="select2data.d_$s1 = new Object();\n";        
 1051:         $result.="select2data.d_$s1.def = new String('".
 1052:             $hashref->{$s1}->{'default'}."');\n";
 1053:         $result.="select2data.d_$s1.values = new Array(";
 1054:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1055:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1056:             @s2values = @{$hashref->{$s1}->{'order'}};
 1057:         }
 1058:         $result.="\"@s2values\");\n";
 1059:         $result.="select2data.d_$s1.texts = new Array(";        
 1060:         my @s2texts;
 1061:         foreach my $value (@s2values) {
 1062:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1063:         }
 1064:         $result.="\"@s2texts\");\n";
 1065:     }
 1066:     $"=' ';
 1067:     $result.= <<"END";
 1068: 
 1069: function select1_changed() {
 1070:     // Determine new choice
 1071:     var newvalue = "d_" + $first.value;
 1072:     // update select2
 1073:     var values     = select2data[newvalue].values;
 1074:     var texts      = select2data[newvalue].texts;
 1075:     var select2def = select2data[newvalue].def;
 1076:     var i;
 1077:     // out with the old
 1078:     for (i = 0; i < $second.options.length; i++) {
 1079:         $second.options[i] = null;
 1080:     }
 1081:     // in with the nuclear
 1082:     for (i=0;i<values.length; i++) {
 1083:         $second.options[i] = new Option(values[i]);
 1084:         $second.options[i].value = values[i];
 1085:         $second.options[i].text = texts[i];
 1086:         if (values[i] == select2def) {
 1087:             $second.options[i].selected = true;
 1088:         }
 1089:     }
 1090: }
 1091: // ]]>
 1092: </script>
 1093: END
 1094:     # output the initial values for the selection lists
 1095:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1096:     my @order = sort(keys(%{$hashref}));
 1097:     if (ref($menuorder) eq 'ARRAY') {
 1098:         @order = @{$menuorder};
 1099:     }
 1100:     foreach my $value (@order) {
 1101:         $result.="    <option value=\"$value\" ";
 1102:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1103:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1104:     }
 1105:     $result .= "</select>\n";
 1106:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1107:     $result .= $middletext;
 1108:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1109:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1110:     
 1111:     my @secondorder = sort(keys(%select2));
 1112:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1113:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1114:     }
 1115:     foreach my $value (@secondorder) {
 1116:         $result.="    <option value=\"$value\" ";        
 1117:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1118:         $result.=">".&mt($select2{$value})."</option>\n";
 1119:     }
 1120:     $result .= "</select>\n";
 1121:     #    return $debug;
 1122:     return $result;
 1123: }   #  end of sub linked_select_forms {
 1124: 
 1125: =pod
 1126: 
 1127: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1128: 
 1129: Returns a string corresponding to an HTML link to the given help
 1130: $topic, where $topic corresponds to the name of a .tex file in
 1131: /home/httpd/html/adm/help/tex, with underscores replaced by
 1132: spaces. 
 1133: 
 1134: $text will optionally be linked to the same topic, allowing you to
 1135: link text in addition to the graphic. If you do not want to link
 1136: text, but wish to specify one of the later parameters, pass an
 1137: empty string. 
 1138: 
 1139: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1140: the link will not open a new window. If false, the link will open
 1141: a new window using Javascript. (Default is false.) 
 1142: 
 1143: $width and $height are optional numerical parameters that will
 1144: override the width and height of the popped up window, which may
 1145: be useful for certain help topics with big pictures included. 
 1146: 
 1147: =cut
 1148: 
 1149: sub help_open_topic {
 1150:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1151:     $text = "" if (not defined $text);
 1152:     $stayOnPage = 0 if (not defined $stayOnPage);
 1153:     $width = 350 if (not defined $width);
 1154:     $height = 400 if (not defined $height);
 1155:     my $filename = $topic;
 1156:     $filename =~ s/ /_/g;
 1157: 
 1158:     my $template = "";
 1159:     my $link;
 1160:     
 1161:     $topic=~s/\W/\_/g;
 1162: 
 1163:     if (!$stayOnPage) {
 1164: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1165:     } else {
 1166: 	$link = "/adm/help/${filename}.hlp";
 1167:     }
 1168: 
 1169:     # Add the text
 1170:     if ($text ne "") {	
 1171: 	$template.='<span class="LC_help_open_topic">'
 1172:                   .'<a target="_top" href="'.$link.'">'
 1173:                   .$text.'</a>';
 1174:     }
 1175: 
 1176:     # (Always) Add the graphic
 1177:     my $title = &mt('Online Help');
 1178:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1179:     if ($imgid ne '') {
 1180:         $imgid = ' id="'.$imgid.'"';
 1181:     }
 1182:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1183:               .'<img src="'.$helpicon.'" border="0"'
 1184:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1185:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
 1186:               .' /></a>';
 1187:     if ($text ne "") {
 1188:         $template.='</span>';
 1189:     }
 1190:     return $template;
 1191: 
 1192: }
 1193: 
 1194: # This is a quicky function for Latex cheatsheet editing, since it 
 1195: # appears in at least four places
 1196: sub helpLatexCheatsheet {
 1197:     my ($topic,$text,$not_author) = @_;
 1198:     my $out;
 1199:     my $addOther = '';
 1200:     if ($topic) {
 1201: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1202: 							       undef, undef, 600).
 1203: 								   '</span> ';
 1204:     }
 1205:     $out = '<span>' # Start cheatsheet
 1206: 	  .$addOther
 1207:           .'<span>'
 1208: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1209: 					       undef,undef,600)
 1210: 	  .'</span> <span>'
 1211: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1212: 					       undef,undef,600)
 1213: 	  .'</span>';
 1214:     unless ($not_author) {
 1215:         $out .= ' <span>'
 1216: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1217: 	                                            undef,undef,600)
 1218: 	       .'</span>';
 1219:     }
 1220:     $out .= '</span>'; # End cheatsheet
 1221:     return $out;
 1222: }
 1223: 
 1224: sub general_help {
 1225:     my $helptopic='Student_Intro';
 1226:     if ($env{'request.role'}=~/^(ca|au)/) {
 1227: 	$helptopic='Authoring_Intro';
 1228:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1229: 	$helptopic='Course_Coordination_Intro';
 1230:     } elsif ($env{'request.role'}=~/^dc/) {
 1231:         $helptopic='Domain_Coordination_Intro';
 1232:     }
 1233:     return $helptopic;
 1234: }
 1235: 
 1236: sub update_help_link {
 1237:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1238:     my $origurl = $ENV{'REQUEST_URI'};
 1239:     $origurl=~s|^/~|/priv/|;
 1240:     my $timestamp = time;
 1241:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1242:         $$datum = &escape($$datum);
 1243:     }
 1244: 
 1245:     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";
 1246:     my $output .= <<"ENDOUTPUT";
 1247: <script type="text/javascript">
 1248: // <![CDATA[
 1249: banner_link = '$banner_link';
 1250: // ]]>
 1251: </script>
 1252: ENDOUTPUT
 1253:     return $output;
 1254: }
 1255: 
 1256: # now just updates the help link and generates a blue icon
 1257: sub help_open_menu {
 1258:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1259: 	= @_;    
 1260:     $stayOnPage = 0 if (not defined $stayOnPage);
 1261:     # only use pop-up help (stayOnPage == 0)
 1262:     # if environment.remote is on (using remote control UI)
 1263:     if ($env{'environment.remote'} eq 'off' ) {
 1264:         $stayOnPage=1;
 1265:     }
 1266:     my $output;
 1267:     if ($component_help) {
 1268: 	if (!$text) {
 1269: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1270: 				       $width,$height);
 1271: 	} else {
 1272: 	    my $help_text;
 1273: 	    $help_text=&unescape($topic);
 1274: 	    $output='<table><tr><td>'.
 1275: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1276: 				 $width,$height).'</td></tr></table>';
 1277: 	}
 1278:     }
 1279:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1280:     return $output.$banner_link;
 1281: }
 1282: 
 1283: sub top_nav_help {
 1284:     my ($text) = @_;
 1285:     $text = &mt($text);
 1286:     my $stay_on_page = 
 1287: 	($env{'environment.remote'} eq 'off' );
 1288:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1289: 	                     : "javascript:helpMenu('open')";
 1290:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1291: 
 1292:     my $title = &mt('Get help');
 1293: 
 1294:     return <<"END";
 1295: $banner_link
 1296:  <a href="$link" title="$title">$text</a>
 1297: END
 1298: }
 1299: 
 1300: sub help_menu_js {
 1301:     my ($text) = @_;
 1302: 
 1303:     my $stayOnPage = 
 1304: 	($env{'environment.remote'} eq 'off' );
 1305: 
 1306:     my $width = 620;
 1307:     my $height = 600;
 1308:     my $helptopic=&general_help();
 1309:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1310:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1311:     my $start_page =
 1312:         &Apache::loncommon::start_page('Help Menu', undef,
 1313: 				       {'frameset'    => 1,
 1314: 					'js_ready'    => 1,
 1315: 					'add_entries' => {
 1316: 					    'border' => '0',
 1317: 					    'rows'   => "110,*",},});
 1318:     my $end_page =
 1319:         &Apache::loncommon::end_page({'frameset' => 1,
 1320: 				      'js_ready' => 1,});
 1321: 
 1322:     my $template .= <<"ENDTEMPLATE";
 1323: <script type="text/javascript">
 1324: // <![CDATA[
 1325: // <!-- BEGIN LON-CAPA Internal
 1326: var banner_link = '';
 1327: function helpMenu(target) {
 1328:     var caller = this;
 1329:     if (target == 'open') {
 1330:         var newWindow = null;
 1331:         try {
 1332:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1333:         }
 1334:         catch(error) {
 1335:             writeHelp(caller);
 1336:             return;
 1337:         }
 1338:         if (newWindow) {
 1339:             caller = newWindow;
 1340:         }
 1341:     }
 1342:     writeHelp(caller);
 1343:     return;
 1344: }
 1345: function writeHelp(caller) {
 1346:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1347:     caller.document.close()
 1348:     caller.focus()
 1349: }
 1350: // END LON-CAPA Internal -->
 1351: // ]]>
 1352: </script>
 1353: ENDTEMPLATE
 1354:     return $template;
 1355: }
 1356: 
 1357: sub help_open_bug {
 1358:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1359:     unless ($env{'user.adv'}) { return ''; }
 1360:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1361:     $text = "" if (not defined $text);
 1362:     $stayOnPage = 0 if (not defined $stayOnPage);
 1363:     if ($env{'environment.remote'} eq 'off' ) {
 1364: 	$stayOnPage=1;
 1365:     }
 1366:     $width = 600 if (not defined $width);
 1367:     $height = 600 if (not defined $height);
 1368: 
 1369:     $topic=~s/\W+/\+/g;
 1370:     my $link='';
 1371:     my $template='';
 1372:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1373: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1374:     if (!$stayOnPage)
 1375:     {
 1376: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1377:     }
 1378:     else
 1379:     {
 1380: 	$link = $url;
 1381:     }
 1382:     # Add the text
 1383:     if ($text ne "")
 1384:     {
 1385: 	$template .= 
 1386:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1387:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1388:     }
 1389: 
 1390:     # Add the graphic
 1391:     my $title = &mt('Report a Bug');
 1392:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1393:     $template .= <<"ENDTEMPLATE";
 1394:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1395: ENDTEMPLATE
 1396:     if ($text ne '') { $template.='</td></tr></table>' };
 1397:     return $template;
 1398: 
 1399: }
 1400: 
 1401: sub help_open_faq {
 1402:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1403:     unless ($env{'user.adv'}) { return ''; }
 1404:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1405:     $text = "" if (not defined $text);
 1406:     $stayOnPage = 0 if (not defined $stayOnPage);
 1407:     if ($env{'environment.remote'} eq 'off' ) {
 1408: 	$stayOnPage=1;
 1409:     }
 1410:     $width = 350 if (not defined $width);
 1411:     $height = 400 if (not defined $height);
 1412: 
 1413:     $topic=~s/\W+/\+/g;
 1414:     my $link='';
 1415:     my $template='';
 1416:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1417:     if (!$stayOnPage)
 1418:     {
 1419: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1420:     }
 1421:     else
 1422:     {
 1423: 	$link = $url;
 1424:     }
 1425: 
 1426:     # Add the text
 1427:     if ($text ne "")
 1428:     {
 1429: 	$template .= 
 1430:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1431:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1432:     }
 1433: 
 1434:     # Add the graphic
 1435:     my $title = &mt('View the FAQ');
 1436:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1437:     $template .= <<"ENDTEMPLATE";
 1438:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1439: ENDTEMPLATE
 1440:     if ($text ne '') { $template.='</td></tr></table>' };
 1441:     return $template;
 1442: 
 1443: }
 1444: 
 1445: ###############################################################
 1446: ###############################################################
 1447: 
 1448: =pod
 1449: 
 1450: =item * &change_content_javascript():
 1451: 
 1452: This and the next function allow you to create small sections of an
 1453: otherwise static HTML page that you can update on the fly with
 1454: Javascript, even in Netscape 4.
 1455: 
 1456: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1457: must be written to the HTML page once. It will prove the Javascript
 1458: function "change(name, content)". Calling the change function with the
 1459: name of the section 
 1460: you want to update, matching the name passed to C<changable_area>, and
 1461: the new content you want to put in there, will put the content into
 1462: that area.
 1463: 
 1464: B<Note>: Netscape 4 only reserves enough space for the changable area
 1465: to contain room for the original contents. You need to "make space"
 1466: for whatever changes you wish to make, and be B<sure> to check your
 1467: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1468: it's adequate for updating a one-line status display, but little more.
 1469: This script will set the space to 100% width, so you only need to
 1470: worry about height in Netscape 4.
 1471: 
 1472: Modern browsers are much less limiting, and if you can commit to the
 1473: user not using Netscape 4, this feature may be used freely with
 1474: pretty much any HTML.
 1475: 
 1476: =cut
 1477: 
 1478: sub change_content_javascript {
 1479:     # If we're on Netscape 4, we need to use Layer-based code
 1480:     if ($env{'browser.type'} eq 'netscape' &&
 1481: 	$env{'browser.version'} =~ /^4\./) {
 1482: 	return (<<NETSCAPE4);
 1483: 	function change(name, content) {
 1484: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1485: 	    doc.open();
 1486: 	    doc.write(content);
 1487: 	    doc.close();
 1488: 	}
 1489: NETSCAPE4
 1490:     } else {
 1491: 	# Otherwise, we need to use semi-standards-compliant code
 1492: 	# (technically, "innerHTML" isn't standard but the equivalent
 1493: 	# is really scary, and every useful browser supports it
 1494: 	return (<<DOMBASED);
 1495: 	function change(name, content) {
 1496: 	    element = document.getElementById(name);
 1497: 	    element.innerHTML = content;
 1498: 	}
 1499: DOMBASED
 1500:     }
 1501: }
 1502: 
 1503: =pod
 1504: 
 1505: =item * &changable_area($name,$origContent):
 1506: 
 1507: This provides a "changable area" that can be modified on the fly via
 1508: the Javascript code provided in C<change_content_javascript>. $name is
 1509: the name you will use to reference the area later; do not repeat the
 1510: same name on a given HTML page more then once. $origContent is what
 1511: the area will originally contain, which can be left blank.
 1512: 
 1513: =cut
 1514: 
 1515: sub changable_area {
 1516:     my ($name, $origContent) = @_;
 1517: 
 1518:     if ($env{'browser.type'} eq 'netscape' &&
 1519: 	$env{'browser.version'} =~ /^4\./) {
 1520: 	# If this is netscape 4, we need to use the Layer tag
 1521: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1522:     } else {
 1523: 	return "<span id='$name'>$origContent</span>";
 1524:     }
 1525: }
 1526: 
 1527: =pod
 1528: 
 1529: =item * &viewport_geometry_js 
 1530: 
 1531: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1532: 
 1533: =cut
 1534: 
 1535: 
 1536: sub viewport_geometry_js { 
 1537:     return <<"GEOMETRY";
 1538: var Geometry = {};
 1539: function init_geometry() {
 1540:     if (Geometry.init) { return };
 1541:     Geometry.init=1;
 1542:     if (window.innerHeight) {
 1543:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1544:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1545:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1546:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1547:     }
 1548:     else if (document.documentElement && document.documentElement.clientHeight) {
 1549:         Geometry.getViewportHeight =
 1550:             function() { return document.documentElement.clientHeight; };
 1551:         Geometry.getViewportWidth =
 1552:             function() { return document.documentElement.clientWidth; };
 1553: 
 1554:         Geometry.getHorizontalScroll =
 1555:             function() { return document.documentElement.scrollLeft; };
 1556:         Geometry.getVerticalScroll =
 1557:             function() { return document.documentElement.scrollTop; };
 1558:     }
 1559:     else if (document.body.clientHeight) {
 1560:         Geometry.getViewportHeight =
 1561:             function() { return document.body.clientHeight; };
 1562:         Geometry.getViewportWidth =
 1563:             function() { return document.body.clientWidth; };
 1564:         Geometry.getHorizontalScroll =
 1565:             function() { return document.body.scrollLeft; };
 1566:         Geometry.getVerticalScroll =
 1567:             function() { return document.body.scrollTop; };
 1568:     }
 1569: }
 1570: 
 1571: GEOMETRY
 1572: }
 1573: 
 1574: =pod
 1575: 
 1576: =item * &viewport_size_js()
 1577: 
 1578: 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. 
 1579: 
 1580: =cut
 1581: 
 1582: sub viewport_size_js {
 1583:     my $geometry = &viewport_geometry_js();
 1584:     return <<"DIMS";
 1585: 
 1586: $geometry
 1587: 
 1588: function getViewportDims(width,height) {
 1589:     init_geometry();
 1590:     width.value = Geometry.getViewportWidth();
 1591:     height.value = Geometry.getViewportHeight();
 1592:     return;
 1593: }
 1594: 
 1595: DIMS
 1596: }
 1597: 
 1598: =pod
 1599: 
 1600: =item * &resize_textarea_js()
 1601: 
 1602: emits the needed javascript to resize a textarea to be as big as possible
 1603: 
 1604: creates a function resize_textrea that takes two IDs first should be
 1605: the id of the element to resize, second should be the id of a div that
 1606: surrounds everything that comes after the textarea, this routine needs
 1607: to be attached to the <body> for the onload and onresize events.
 1608: 
 1609: =back
 1610: 
 1611: =cut
 1612: 
 1613: sub resize_textarea_js {
 1614:     my $geometry = &viewport_geometry_js();
 1615:     return <<"RESIZE";
 1616:     <script type="text/javascript">
 1617: // <![CDATA[
 1618: $geometry
 1619: 
 1620: function getX(element) {
 1621:     var x = 0;
 1622:     while (element) {
 1623: 	x += element.offsetLeft;
 1624: 	element = element.offsetParent;
 1625:     }
 1626:     return x;
 1627: }
 1628: function getY(element) {
 1629:     var y = 0;
 1630:     while (element) {
 1631: 	y += element.offsetTop;
 1632: 	element = element.offsetParent;
 1633:     }
 1634:     return y;
 1635: }
 1636: 
 1637: 
 1638: function resize_textarea(textarea_id,bottom_id) {
 1639:     init_geometry();
 1640:     var textarea        = document.getElementById(textarea_id);
 1641:     //alert(textarea);
 1642: 
 1643:     var textarea_top    = getY(textarea);
 1644:     var textarea_height = textarea.offsetHeight;
 1645:     var bottom          = document.getElementById(bottom_id);
 1646:     var bottom_top      = getY(bottom);
 1647:     var bottom_height   = bottom.offsetHeight;
 1648:     var window_height   = Geometry.getViewportHeight();
 1649:     var fudge           = 23;
 1650:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1651:     if (new_height < 300) {
 1652: 	new_height = 300;
 1653:     }
 1654:     textarea.style.height=new_height+'px';
 1655: }
 1656: // ]]>
 1657: </script>
 1658: RESIZE
 1659: 
 1660: }
 1661: 
 1662: =pod
 1663: 
 1664: =head1 Excel and CSV file utility routines
 1665: 
 1666: =over 4
 1667: 
 1668: =cut
 1669: 
 1670: ###############################################################
 1671: ###############################################################
 1672: 
 1673: =pod
 1674: 
 1675: =item * &csv_translate($text) 
 1676: 
 1677: Translate $text to allow it to be output as a 'comma separated values' 
 1678: format.
 1679: 
 1680: =cut
 1681: 
 1682: ###############################################################
 1683: ###############################################################
 1684: sub csv_translate {
 1685:     my $text = shift;
 1686:     $text =~ s/\"/\"\"/g;
 1687:     $text =~ s/\n/ /g;
 1688:     return $text;
 1689: }
 1690: 
 1691: ###############################################################
 1692: ###############################################################
 1693: 
 1694: =pod
 1695: 
 1696: =item * &define_excel_formats()
 1697: 
 1698: Define some commonly used Excel cell formats.
 1699: 
 1700: Currently supported formats:
 1701: 
 1702: =over 4
 1703: 
 1704: =item header
 1705: 
 1706: =item bold
 1707: 
 1708: =item h1
 1709: 
 1710: =item h2
 1711: 
 1712: =item h3
 1713: 
 1714: =item h4
 1715: 
 1716: =item i
 1717: 
 1718: =item date
 1719: 
 1720: =back
 1721: 
 1722: Inputs: $workbook
 1723: 
 1724: Returns: $format, a hash reference.
 1725: 
 1726: =cut
 1727: 
 1728: ###############################################################
 1729: ###############################################################
 1730: sub define_excel_formats {
 1731:     my ($workbook) = @_;
 1732:     my $format;
 1733:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1734:                                                 bottom    => 1,
 1735:                                                 align     => 'center');
 1736:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1737:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1738:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1739:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1740:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1741:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1742:     $format->{'date'} = $workbook->add_format(num_format=>
 1743:                                             'mm/dd/yyyy hh:mm:ss');
 1744:     return $format;
 1745: }
 1746: 
 1747: ###############################################################
 1748: ###############################################################
 1749: 
 1750: =pod
 1751: 
 1752: =item * &create_workbook()
 1753: 
 1754: Create an Excel worksheet.  If it fails, output message on the
 1755: request object and return undefs.
 1756: 
 1757: Inputs: Apache request object
 1758: 
 1759: Returns (undef) on failure, 
 1760:     Excel worksheet object, scalar with filename, and formats 
 1761:     from &Apache::loncommon::define_excel_formats on success
 1762: 
 1763: =cut
 1764: 
 1765: ###############################################################
 1766: ###############################################################
 1767: sub create_workbook {
 1768:     my ($r) = @_;
 1769:         #
 1770:     # Create the excel spreadsheet
 1771:     my $filename = '/prtspool/'.
 1772:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1773:         time.'_'.rand(1000000000).'.xls';
 1774:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1775:     if (! defined($workbook)) {
 1776:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1777:         $r->print(
 1778:             '<p class="LC_error">'
 1779:            .&mt('Problems occurred in creating the new Excel file.')
 1780:            .' '.&mt('This error has been logged.')
 1781:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1782:            .'</p>'
 1783:         );
 1784:         return (undef);
 1785:     }
 1786:     #
 1787:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1788:     #
 1789:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1790:     return ($workbook,$filename,$format);
 1791: }
 1792: 
 1793: ###############################################################
 1794: ###############################################################
 1795: 
 1796: =pod
 1797: 
 1798: =item * &create_text_file()
 1799: 
 1800: Create a file to write to and eventually make available to the user.
 1801: If file creation fails, outputs an error message on the request object and 
 1802: return undefs.
 1803: 
 1804: Inputs: Apache request object, and file suffix
 1805: 
 1806: Returns (undef) on failure, 
 1807:     Filehandle and filename on success.
 1808: 
 1809: =cut
 1810: 
 1811: ###############################################################
 1812: ###############################################################
 1813: sub create_text_file {
 1814:     my ($r,$suffix) = @_;
 1815:     if (! defined($suffix)) { $suffix = 'txt'; };
 1816:     my $fh;
 1817:     my $filename = '/prtspool/'.
 1818:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1819:         time.'_'.rand(1000000000).'.'.$suffix;
 1820:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1821:     if (! defined($fh)) {
 1822:         $r->log_error("Couldn't open $filename for output $!");
 1823:         $r->print(
 1824:             '<p class="LC_error">'
 1825:            .&mt('Problems occurred in creating the output file.')
 1826:            .' '.&mt('This error has been logged.')
 1827:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1828:            .'</p>'
 1829:         );
 1830:     }
 1831:     return ($fh,$filename)
 1832: }
 1833: 
 1834: 
 1835: =pod 
 1836: 
 1837: =back
 1838: 
 1839: =cut
 1840: 
 1841: ###############################################################
 1842: ##        Home server <option> list generating code          ##
 1843: ###############################################################
 1844: 
 1845: # ------------------------------------------
 1846: 
 1847: sub domain_select {
 1848:     my ($name,$value,$multiple)=@_;
 1849:     my %domains=map { 
 1850: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1851:     } &Apache::lonnet::all_domains();
 1852:     if ($multiple) {
 1853: 	$domains{''}=&mt('Any domain');
 1854: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1855: 	return &multiple_select_form($name,$value,4,\%domains);
 1856:     } else {
 1857: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1858: 	return &select_form($name,$value,\%domains);
 1859:     }
 1860: }
 1861: 
 1862: #-------------------------------------------
 1863: 
 1864: =pod
 1865: 
 1866: =head1 Routines for form select boxes
 1867: 
 1868: =over 4
 1869: 
 1870: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1871: 
 1872: Returns a string containing a <select> element int multiple mode
 1873: 
 1874: 
 1875: Args:
 1876:   $name - name of the <select> element
 1877:   $value - scalar or array ref of values that should already be selected
 1878:   $size - number of rows long the select element is
 1879:   $hash - the elements should be 'option' => 'shown text'
 1880:           (shown text should already have been &mt())
 1881:   $order - (optional) array ref of the order to show the elements in
 1882: 
 1883: =cut
 1884: 
 1885: #-------------------------------------------
 1886: sub multiple_select_form {
 1887:     my ($name,$value,$size,$hash,$order)=@_;
 1888:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1889:     my $output='';
 1890:     if (! defined($size)) {
 1891:         $size = 4;
 1892:         if (scalar(keys(%$hash))<4) {
 1893:             $size = scalar(keys(%$hash));
 1894:         }
 1895:     }
 1896:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1897:     my @order;
 1898:     if (ref($order) eq 'ARRAY')  {
 1899:         @order = @{$order};
 1900:     } else {
 1901:         @order = sort(keys(%$hash));
 1902:     }
 1903:     if (exists($$hash{'select_form_order'})) {
 1904:         @order = @{$$hash{'select_form_order'}};
 1905:     }
 1906:         
 1907:     foreach my $key (@order) {
 1908:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1909:         $output.='selected="selected" ' if ($selected{$key});
 1910:         $output.='>'.$hash->{$key}."</option>\n";
 1911:     }
 1912:     $output.="</select>\n";
 1913:     return $output;
 1914: }
 1915: 
 1916: #-------------------------------------------
 1917: 
 1918: =pod
 1919: 
 1920: =item * &select_form($defdom,$name,$hashref,$onchange)
 1921: 
 1922: Returns a string containing a <select name='$name' size='1'> form to 
 1923: allow a user to select options from a ref to a hash containing:
 1924: option_name => displayed text. An optional $onchange can include
 1925: a javascript onchange item, e.g., onchange="this.form.submit();"
 1926: 
 1927: See lonrights.pm for an example invocation and use.
 1928: 
 1929: =cut
 1930: 
 1931: #-------------------------------------------
 1932: sub select_form {
 1933:     my ($def,$name,$hashref,$onchange) = @_;
 1934:     return unless (ref($hashref) eq 'HASH');
 1935:     if ($onchange) {
 1936:         $onchange = ' onchange="'.$onchange.'"';
 1937:     }
 1938:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1939:     my @keys;
 1940:     if (exists($hashref->{'select_form_order'})) {
 1941:         @keys=@{$hashref->{'select_form_order'}};
 1942:     } else {
 1943:         @keys=sort(keys(%{$hashref}));
 1944:     }
 1945:     foreach my $key (@keys) {
 1946:         $selectform.=
 1947: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1948:             ($key eq $def ? 'selected="selected" ' : '').
 1949:                 ">".$hashref->{$key}."</option>\n";
 1950:     }
 1951:     $selectform.="</select>";
 1952:     return $selectform;
 1953: }
 1954: 
 1955: # For display filters
 1956: 
 1957: sub display_filter {
 1958:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1959:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1960:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1961: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1962: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1963: 	   '</label></span> <span class="LC_nobreak">'.
 1964:            &mt('Filter [_1]',
 1965: 	   &select_form($env{'form.displayfilter'},
 1966: 			'displayfilter',
 1967: 			{'currentfolder' => 'Current folder/page',
 1968: 			 'containing' => 'Containing phrase',
 1969: 			 'none' => 'None'})).
 1970: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1971: }
 1972: 
 1973: sub gradeleveldescription {
 1974:     my $gradelevel=shift;
 1975:     my %gradelevels=(0 => 'Not specified',
 1976: 		     1 => 'Grade 1',
 1977: 		     2 => 'Grade 2',
 1978: 		     3 => 'Grade 3',
 1979: 		     4 => 'Grade 4',
 1980: 		     5 => 'Grade 5',
 1981: 		     6 => 'Grade 6',
 1982: 		     7 => 'Grade 7',
 1983: 		     8 => 'Grade 8',
 1984: 		     9 => 'Grade 9',
 1985: 		     10 => 'Grade 10',
 1986: 		     11 => 'Grade 11',
 1987: 		     12 => 'Grade 12',
 1988: 		     13 => 'Grade 13',
 1989: 		     14 => '100 Level',
 1990: 		     15 => '200 Level',
 1991: 		     16 => '300 Level',
 1992: 		     17 => '400 Level',
 1993: 		     18 => 'Graduate Level');
 1994:     return &mt($gradelevels{$gradelevel});
 1995: }
 1996: 
 1997: sub select_level_form {
 1998:     my ($deflevel,$name)=@_;
 1999:     unless ($deflevel) { $deflevel=0; }
 2000:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2001:     for (my $i=0; $i<=18; $i++) {
 2002:         $selectform.="<option value=\"$i\" ".
 2003:             ($i==$deflevel ? 'selected="selected" ' : '').
 2004:                 ">".&gradeleveldescription($i)."</option>\n";
 2005:     }
 2006:     $selectform.="</select>";
 2007:     return $selectform;
 2008: }
 2009: 
 2010: #-------------------------------------------
 2011: 
 2012: =pod
 2013: 
 2014: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2015: 
 2016: Returns a string containing a <select name='$name' size='1'> form to 
 2017: allow a user to select the domain to preform an operation in.  
 2018: See loncreateuser.pm for an example invocation and use.
 2019: 
 2020: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2021: selected");
 2022: 
 2023: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2024: 
 2025: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 2026: 
 2027: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2028: 
 2029: =cut
 2030: 
 2031: #-------------------------------------------
 2032: sub select_dom_form {
 2033:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2034:     if ($onchange) {
 2035:         $onchange = ' onchange="'.$onchange.'"';
 2036:     }
 2037:     my @domains;
 2038:     if (ref($incdoms) eq 'ARRAY') {
 2039:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2040:     } else {
 2041:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2042:     }
 2043:     if ($includeempty) { @domains=('',@domains); }
 2044:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2045:     foreach my $dom (@domains) {
 2046:         $selectdomain.="<option value=\"$dom\" ".
 2047:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2048:         if ($showdomdesc) {
 2049:             if ($dom ne '') {
 2050:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2051:                 if ($domdesc ne '') {
 2052:                     $selectdomain .= ' ('.$domdesc.')';
 2053:                 }
 2054:             } 
 2055:         }
 2056:         $selectdomain .= "</option>\n";
 2057:     }
 2058:     $selectdomain.="</select>";
 2059:     return $selectdomain;
 2060: }
 2061: 
 2062: #-------------------------------------------
 2063: 
 2064: =pod
 2065: 
 2066: =item * &home_server_form_item($domain,$name,$defaultflag)
 2067: 
 2068: input: 4 arguments (two required, two optional) - 
 2069:     $domain - domain of new user
 2070:     $name - name of form element
 2071:     $default - Value of 'default' causes a default item to be first 
 2072:                             option, and selected by default. 
 2073:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2074:                             if 1 server found, or default, if 0 found.
 2075: output: returns 2 items: 
 2076: (a) form element which contains either:
 2077:    (i) <select name="$name">
 2078:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2079:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2080:        </select>
 2081:        form item if there are multiple library servers in $domain, or
 2082:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2083:        if there is only one library server in $domain.
 2084: 
 2085: (b) number of library servers found.
 2086: 
 2087: See loncreateuser.pm for example of use.
 2088: 
 2089: =cut
 2090: 
 2091: #-------------------------------------------
 2092: sub home_server_form_item {
 2093:     my ($domain,$name,$default,$hide) = @_;
 2094:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2095:     my $result;
 2096:     my $numlib = keys(%servers);
 2097:     if ($numlib > 1) {
 2098:         $result .= '<select name="'.$name.'" />'."\n";
 2099:         if ($default) {
 2100:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2101:                        '</option>'."\n";
 2102:         }
 2103:         foreach my $hostid (sort(keys(%servers))) {
 2104:             $result.= '<option value="'.$hostid.'">'.
 2105: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2106:         }
 2107:         $result .= '</select>'."\n";
 2108:     } elsif ($numlib == 1) {
 2109:         my $hostid;
 2110:         foreach my $item (keys(%servers)) {
 2111:             $hostid = $item;
 2112:         }
 2113:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2114:                    $hostid.'" />';
 2115:                    if (!$hide) {
 2116:                        $result .= $hostid.' '.$servers{$hostid};
 2117:                    }
 2118:                    $result .= "\n";
 2119:     } elsif ($default) {
 2120:         $result .= '<input type="hidden" name="'.$name.
 2121:                    '" value="default" />';
 2122:                    if (!$hide) {
 2123:                        $result .= &mt('default');
 2124:                    }
 2125:                    $result .= "\n";
 2126:     }
 2127:     return ($result,$numlib);
 2128: }
 2129: 
 2130: =pod
 2131: 
 2132: =back 
 2133: 
 2134: =cut
 2135: 
 2136: ###############################################################
 2137: ##                  Decoding User Agent                      ##
 2138: ###############################################################
 2139: 
 2140: =pod
 2141: 
 2142: =head1 Decoding the User Agent
 2143: 
 2144: =over 4
 2145: 
 2146: =item * &decode_user_agent()
 2147: 
 2148: Inputs: $r
 2149: 
 2150: Outputs:
 2151: 
 2152: =over 4
 2153: 
 2154: =item * $httpbrowser
 2155: 
 2156: =item * $clientbrowser
 2157: 
 2158: =item * $clientversion
 2159: 
 2160: =item * $clientmathml
 2161: 
 2162: =item * $clientunicode
 2163: 
 2164: =item * $clientos
 2165: 
 2166: =back
 2167: 
 2168: =back 
 2169: 
 2170: =cut
 2171: 
 2172: ###############################################################
 2173: ###############################################################
 2174: sub decode_user_agent {
 2175:     my ($r)=@_;
 2176:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2177:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2178:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2179:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2180:     my $clientbrowser='unknown';
 2181:     my $clientversion='0';
 2182:     my $clientmathml='';
 2183:     my $clientunicode='0';
 2184:     for (my $i=0;$i<=$#browsertype;$i++) {
 2185:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2186: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2187: 	    $clientbrowser=$bname;
 2188:             $httpbrowser=~/$vreg/i;
 2189: 	    $clientversion=$1;
 2190:             $clientmathml=($clientversion>=$minv);
 2191:             $clientunicode=($clientversion>=$univ);
 2192: 	}
 2193:     }
 2194:     my $clientos='unknown';
 2195:     if (($httpbrowser=~/linux/i) ||
 2196:         ($httpbrowser=~/unix/i) ||
 2197:         ($httpbrowser=~/ux/i) ||
 2198:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2199:     if (($httpbrowser=~/vax/i) ||
 2200:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2201:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2202:     if (($httpbrowser=~/mac/i) ||
 2203:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2204:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2205:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2206:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2207:             $clientunicode,$clientos,);
 2208: }
 2209: 
 2210: ###############################################################
 2211: ##    Authentication changing form generation subroutines    ##
 2212: ###############################################################
 2213: ##
 2214: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2215: ## hash, and have reasonable default values.
 2216: ##
 2217: ##    formname = the name given in the <form> tag.
 2218: #-------------------------------------------
 2219: 
 2220: =pod
 2221: 
 2222: =head1 Authentication Routines
 2223: 
 2224: =over 4
 2225: 
 2226: =item * &authform_xxxxxx()
 2227: 
 2228: The authform_xxxxxx subroutines provide javascript and html forms which 
 2229: handle some of the conveniences required for authentication forms.  
 2230: This is not an optimal method, but it works.  
 2231: 
 2232: =over 4
 2233: 
 2234: =item * authform_header
 2235: 
 2236: =item * authform_authorwarning
 2237: 
 2238: =item * authform_nochange
 2239: 
 2240: =item * authform_kerberos
 2241: 
 2242: =item * authform_internal
 2243: 
 2244: =item * authform_filesystem
 2245: 
 2246: =back
 2247: 
 2248: See loncreateuser.pm for invocation and use examples.
 2249: 
 2250: =cut
 2251: 
 2252: #-------------------------------------------
 2253: sub authform_header{  
 2254:     my %in = (
 2255:         formname => 'cu',
 2256:         kerb_def_dom => '',
 2257:         @_,
 2258:     );
 2259:     $in{'formname'} = 'document.' . $in{'formname'};
 2260:     my $result='';
 2261: 
 2262: #---------------------------------------------- Code for upper case translation
 2263:     my $Javascript_toUpperCase;
 2264:     unless ($in{kerb_def_dom}) {
 2265:         $Javascript_toUpperCase =<<"END";
 2266:         switch (choice) {
 2267:            case 'krb': currentform.elements[choicearg].value =
 2268:                currentform.elements[choicearg].value.toUpperCase();
 2269:                break;
 2270:            default:
 2271:         }
 2272: END
 2273:     } else {
 2274:         $Javascript_toUpperCase = "";
 2275:     }
 2276: 
 2277:     my $radioval = "'nochange'";
 2278:     if (defined($in{'curr_authtype'})) {
 2279:         if ($in{'curr_authtype'} ne '') {
 2280:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2281:         }
 2282:     }
 2283:     my $argfield = 'null';
 2284:     if (defined($in{'mode'})) {
 2285:         if ($in{'mode'} eq 'modifycourse')  {
 2286:             if (defined($in{'curr_autharg'})) {
 2287:                 if ($in{'curr_autharg'} ne '') {
 2288:                     $argfield = "'$in{'curr_autharg'}'";
 2289:                 }
 2290:             }
 2291:         }
 2292:     }
 2293: 
 2294:     $result.=<<"END";
 2295: var current = new Object();
 2296: current.radiovalue = $radioval;
 2297: current.argfield = $argfield;
 2298: 
 2299: function changed_radio(choice,currentform) {
 2300:     var choicearg = choice + 'arg';
 2301:     // If a radio button in changed, we need to change the argfield
 2302:     if (current.radiovalue != choice) {
 2303:         current.radiovalue = choice;
 2304:         if (current.argfield != null) {
 2305:             currentform.elements[current.argfield].value = '';
 2306:         }
 2307:         if (choice == 'nochange') {
 2308:             current.argfield = null;
 2309:         } else {
 2310:             current.argfield = choicearg;
 2311:             switch(choice) {
 2312:                 case 'krb': 
 2313:                     currentform.elements[current.argfield].value = 
 2314:                         "$in{'kerb_def_dom'}";
 2315:                 break;
 2316:               default:
 2317:                 break;
 2318:             }
 2319:         }
 2320:     }
 2321:     return;
 2322: }
 2323: 
 2324: function changed_text(choice,currentform) {
 2325:     var choicearg = choice + 'arg';
 2326:     if (currentform.elements[choicearg].value !='') {
 2327:         $Javascript_toUpperCase
 2328:         // clear old field
 2329:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2330:             currentform.elements[current.argfield].value = '';
 2331:         }
 2332:         current.argfield = choicearg;
 2333:     }
 2334:     set_auth_radio_buttons(choice,currentform);
 2335:     return;
 2336: }
 2337: 
 2338: function set_auth_radio_buttons(newvalue,currentform) {
 2339:     var numauthchoices = currentform.login.length;
 2340:     if (typeof numauthchoices  == "undefined") {
 2341:         return;
 2342:     }
 2343:     var i=0;
 2344:     while (i < numauthchoices) {
 2345:         if (currentform.login[i].value == newvalue) { break; }
 2346:         i++;
 2347:     }
 2348:     if (i == numauthchoices) {
 2349:         return;
 2350:     }
 2351:     current.radiovalue = newvalue;
 2352:     currentform.login[i].checked = true;
 2353:     return;
 2354: }
 2355: END
 2356:     return $result;
 2357: }
 2358: 
 2359: sub authform_authorwarning{
 2360:     my $result='';
 2361:     $result='<i>'.
 2362:         &mt('As a general rule, only authors or co-authors should be '.
 2363:             'filesystem authenticated '.
 2364:             '(which allows access to the server filesystem).')."</i>\n";
 2365:     return $result;
 2366: }
 2367: 
 2368: sub authform_nochange{  
 2369:     my %in = (
 2370:               formname => 'document.cu',
 2371:               kerb_def_dom => 'MSU.EDU',
 2372:               @_,
 2373:           );
 2374:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2375:     my $result;
 2376:     if (keys(%can_assign) == 0) {
 2377:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2378:     } else {
 2379:         $result = '<label>'.&mt('[_1] Do not change login data',
 2380:                   '<input type="radio" name="login" value="nochange" '.
 2381:                   'checked="checked" onclick="'.
 2382:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2383: 	    '</label>';
 2384:     }
 2385:     return $result;
 2386: }
 2387: 
 2388: sub authform_kerberos {
 2389:     my %in = (
 2390:               formname => 'document.cu',
 2391:               kerb_def_dom => 'MSU.EDU',
 2392:               kerb_def_auth => 'krb4',
 2393:               @_,
 2394:               );
 2395:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2396:         $autharg,$jscall);
 2397:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2398:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2399:        $check5 = ' checked="checked"';
 2400:     } else {
 2401:        $check4 = ' checked="checked"';
 2402:     }
 2403:     $krbarg = $in{'kerb_def_dom'};
 2404:     if (defined($in{'curr_authtype'})) {
 2405:         if ($in{'curr_authtype'} eq 'krb') {
 2406:             $krbcheck = ' checked="checked"';
 2407:             if (defined($in{'mode'})) {
 2408:                 if ($in{'mode'} eq 'modifyuser') {
 2409:                     $krbcheck = '';
 2410:                 }
 2411:             }
 2412:             if (defined($in{'curr_kerb_ver'})) {
 2413:                 if ($in{'curr_krb_ver'} eq '5') {
 2414:                     $check5 = ' checked="checked"';
 2415:                     $check4 = '';
 2416:                 } else {
 2417:                     $check4 = ' checked="checked"';
 2418:                     $check5 = '';
 2419:                 }
 2420:             }
 2421:             if (defined($in{'curr_autharg'})) {
 2422:                 $krbarg = $in{'curr_autharg'};
 2423:             }
 2424:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2425:                 if (defined($in{'curr_autharg'})) {
 2426:                     $result = 
 2427:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2428:         $in{'curr_autharg'},$krbver);
 2429:                 } else {
 2430:                     $result =
 2431:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2432:                 }
 2433:                 return $result; 
 2434:             }
 2435:         }
 2436:     } else {
 2437:         if ($authnum == 1) {
 2438:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2439:         }
 2440:     }
 2441:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2442:         return;
 2443:     } elsif ($authtype eq '') {
 2444:         if (defined($in{'mode'})) {
 2445:             if ($in{'mode'} eq 'modifycourse') {
 2446:                 if ($authnum == 1) {
 2447:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2448:                 }
 2449:             }
 2450:         }
 2451:     }
 2452:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2453:     if ($authtype eq '') {
 2454:         $authtype = '<input type="radio" name="login" value="krb" '.
 2455:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2456:                     $krbcheck.' />';
 2457:     }
 2458:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2459:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2460:          $in{'curr_authtype'} eq 'krb5') ||
 2461:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2462:          $in{'curr_authtype'} eq 'krb4')) {
 2463:         $result .= &mt
 2464:         ('[_1] Kerberos authenticated with domain [_2] '.
 2465:          '[_3] Version 4 [_4] Version 5 [_5]',
 2466:          '<label>'.$authtype,
 2467:          '</label><input type="text" size="10" name="krbarg" '.
 2468:              'value="'.$krbarg.'" '.
 2469:              'onchange="'.$jscall.'" />',
 2470:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2471:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2472: 	 '</label>');
 2473:     } elsif ($can_assign{'krb4'}) {
 2474:         $result .= &mt
 2475:         ('[_1] Kerberos authenticated with domain [_2] '.
 2476:          '[_3] Version 4 [_4]',
 2477:          '<label>'.$authtype,
 2478:          '</label><input type="text" size="10" name="krbarg" '.
 2479:              'value="'.$krbarg.'" '.
 2480:              'onchange="'.$jscall.'" />',
 2481:          '<label><input type="hidden" name="krbver" value="4" />',
 2482:          '</label>');
 2483:     } elsif ($can_assign{'krb5'}) {
 2484:         $result .= &mt
 2485:         ('[_1] Kerberos authenticated with domain [_2] '.
 2486:          '[_3] Version 5 [_4]',
 2487:          '<label>'.$authtype,
 2488:          '</label><input type="text" size="10" name="krbarg" '.
 2489:              'value="'.$krbarg.'" '.
 2490:              'onchange="'.$jscall.'" />',
 2491:          '<label><input type="hidden" name="krbver" value="5" />',
 2492:          '</label>');
 2493:     }
 2494:     return $result;
 2495: }
 2496: 
 2497: sub authform_internal{  
 2498:     my %in = (
 2499:                 formname => 'document.cu',
 2500:                 kerb_def_dom => 'MSU.EDU',
 2501:                 @_,
 2502:                 );
 2503:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2504:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2505:     if (defined($in{'curr_authtype'})) {
 2506:         if ($in{'curr_authtype'} eq 'int') {
 2507:             if ($can_assign{'int'}) {
 2508:                 $intcheck = 'checked="checked" ';
 2509:                 if (defined($in{'mode'})) {
 2510:                     if ($in{'mode'} eq 'modifyuser') {
 2511:                         $intcheck = '';
 2512:                     }
 2513:                 }
 2514:                 if (defined($in{'curr_autharg'})) {
 2515:                     $intarg = $in{'curr_autharg'};
 2516:                 }
 2517:             } else {
 2518:                 $result = &mt('Currently internally authenticated.');
 2519:                 return $result;
 2520:             }
 2521:         }
 2522:     } else {
 2523:         if ($authnum == 1) {
 2524:             $authtype = '<input type="hidden" name="login" value="int" />';
 2525:         }
 2526:     }
 2527:     if (!$can_assign{'int'}) {
 2528:         return;
 2529:     } elsif ($authtype eq '') {
 2530:         if (defined($in{'mode'})) {
 2531:             if ($in{'mode'} eq 'modifycourse') {
 2532:                 if ($authnum == 1) {
 2533:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2534:                 }
 2535:             }
 2536:         }
 2537:     }
 2538:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2539:     if ($authtype eq '') {
 2540:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2541:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2542:     }
 2543:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2544:                $intarg.'" onchange="'.$jscall.'" />';
 2545:     $result = &mt
 2546:         ('[_1] Internally authenticated (with initial password [_2])',
 2547:          '<label>'.$authtype,'</label>'.$autharg);
 2548:     $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>';
 2549:     return $result;
 2550: }
 2551: 
 2552: sub authform_local{  
 2553:     my %in = (
 2554:               formname => 'document.cu',
 2555:               kerb_def_dom => 'MSU.EDU',
 2556:               @_,
 2557:               );
 2558:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2559:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2560:     if (defined($in{'curr_authtype'})) {
 2561:         if ($in{'curr_authtype'} eq 'loc') {
 2562:             if ($can_assign{'loc'}) {
 2563:                 $loccheck = 'checked="checked" ';
 2564:                 if (defined($in{'mode'})) {
 2565:                     if ($in{'mode'} eq 'modifyuser') {
 2566:                         $loccheck = '';
 2567:                     }
 2568:                 }
 2569:                 if (defined($in{'curr_autharg'})) {
 2570:                     $locarg = $in{'curr_autharg'};
 2571:                 }
 2572:             } else {
 2573:                 $result = &mt('Currently using local (institutional) authentication.');
 2574:                 return $result;
 2575:             }
 2576:         }
 2577:     } else {
 2578:         if ($authnum == 1) {
 2579:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2580:         }
 2581:     }
 2582:     if (!$can_assign{'loc'}) {
 2583:         return;
 2584:     } elsif ($authtype eq '') {
 2585:         if (defined($in{'mode'})) {
 2586:             if ($in{'mode'} eq 'modifycourse') {
 2587:                 if ($authnum == 1) {
 2588:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2589:                 }
 2590:             }
 2591:         }
 2592:     }
 2593:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2594:     if ($authtype eq '') {
 2595:         $authtype = '<input type="radio" name="login" value="loc" '.
 2596:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2597:                     $jscall.'" />';
 2598:     }
 2599:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2600:                $locarg.'" onchange="'.$jscall.'" />';
 2601:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2602:                   '<label>'.$authtype,'</label>'.$autharg);
 2603:     return $result;
 2604: }
 2605: 
 2606: sub authform_filesystem{  
 2607:     my %in = (
 2608:               formname => 'document.cu',
 2609:               kerb_def_dom => 'MSU.EDU',
 2610:               @_,
 2611:               );
 2612:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2613:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2614:     if (defined($in{'curr_authtype'})) {
 2615:         if ($in{'curr_authtype'} eq 'fsys') {
 2616:             if ($can_assign{'fsys'}) {
 2617:                 $fsyscheck = 'checked="checked" ';
 2618:                 if (defined($in{'mode'})) {
 2619:                     if ($in{'mode'} eq 'modifyuser') {
 2620:                         $fsyscheck = '';
 2621:                     }
 2622:                 }
 2623:             } else {
 2624:                 $result = &mt('Currently Filesystem Authenticated.');
 2625:                 return $result;
 2626:             }           
 2627:         }
 2628:     } else {
 2629:         if ($authnum == 1) {
 2630:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2631:         }
 2632:     }
 2633:     if (!$can_assign{'fsys'}) {
 2634:         return;
 2635:     } elsif ($authtype eq '') {
 2636:         if (defined($in{'mode'})) {
 2637:             if ($in{'mode'} eq 'modifycourse') {
 2638:                 if ($authnum == 1) {
 2639:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2640:                 }
 2641:             }
 2642:         }
 2643:     }
 2644:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2645:     if ($authtype eq '') {
 2646:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2647:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2648:                     $jscall.'" />';
 2649:     }
 2650:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2651:                ' onchange="'.$jscall.'" />';
 2652:     $result = &mt
 2653:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2654:          '<label><input type="radio" name="login" value="fsys" '.
 2655:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2656:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2657:                   'onchange="'.$jscall.'" />');
 2658:     return $result;
 2659: }
 2660: 
 2661: sub get_assignable_auth {
 2662:     my ($dom) = @_;
 2663:     if ($dom eq '') {
 2664:         $dom = $env{'request.role.domain'};
 2665:     }
 2666:     my %can_assign = (
 2667:                           krb4 => 1,
 2668:                           krb5 => 1,
 2669:                           int  => 1,
 2670:                           loc  => 1,
 2671:                      );
 2672:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2673:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2674:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2675:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2676:             my $context;
 2677:             if ($env{'request.role'} =~ /^au/) {
 2678:                 $context = 'author';
 2679:             } elsif ($env{'request.role'} =~ /^dc/) {
 2680:                 $context = 'domain';
 2681:             } elsif ($env{'request.course.id'}) {
 2682:                 $context = 'course';
 2683:             }
 2684:             if ($context) {
 2685:                 if (ref($authhash->{$context}) eq 'HASH') {
 2686:                    %can_assign = %{$authhash->{$context}}; 
 2687:                 }
 2688:             }
 2689:         }
 2690:     }
 2691:     my $authnum = 0;
 2692:     foreach my $key (keys(%can_assign)) {
 2693:         if ($can_assign{$key}) {
 2694:             $authnum ++;
 2695:         }
 2696:     }
 2697:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2698:         $authnum --;
 2699:     }
 2700:     return ($authnum,%can_assign);
 2701: }
 2702: 
 2703: ###############################################################
 2704: ##    Get Kerberos Defaults for Domain                 ##
 2705: ###############################################################
 2706: ##
 2707: ## Returns default kerberos version and an associated argument
 2708: ## as listed in file domain.tab. If not listed, provides
 2709: ## appropriate default domain and kerberos version.
 2710: ##
 2711: #-------------------------------------------
 2712: 
 2713: =pod
 2714: 
 2715: =item * &get_kerberos_defaults()
 2716: 
 2717: get_kerberos_defaults($target_domain) returns the default kerberos
 2718: version and domain. If not found, it defaults to version 4 and the 
 2719: domain of the server.
 2720: 
 2721: =over 4
 2722: 
 2723: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2724: 
 2725: =back
 2726: 
 2727: =back
 2728: 
 2729: =cut
 2730: 
 2731: #-------------------------------------------
 2732: sub get_kerberos_defaults {
 2733:     my $domain=shift;
 2734:     my ($krbdef,$krbdefdom);
 2735:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2736:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2737:         $krbdef = $domdefaults{'auth_def'};
 2738:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2739:     } else {
 2740:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2741:         my $krbdefdom=$1;
 2742:         $krbdefdom=~tr/a-z/A-Z/;
 2743:         $krbdef = "krb4";
 2744:     }
 2745:     return ($krbdef,$krbdefdom);
 2746: }
 2747: 
 2748: 
 2749: ###############################################################
 2750: ##                Thesaurus Functions                        ##
 2751: ###############################################################
 2752: 
 2753: =pod
 2754: 
 2755: =head1 Thesaurus Functions
 2756: 
 2757: =over 4
 2758: 
 2759: =item * &initialize_keywords()
 2760: 
 2761: Initializes the package variable %Keywords if it is empty.  Uses the
 2762: package variable $thesaurus_db_file.
 2763: 
 2764: =cut
 2765: 
 2766: ###################################################
 2767: 
 2768: sub initialize_keywords {
 2769:     return 1 if (scalar keys(%Keywords));
 2770:     # If we are here, %Keywords is empty, so fill it up
 2771:     #   Make sure the file we need exists...
 2772:     if (! -e $thesaurus_db_file) {
 2773:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2774:                                  " failed because it does not exist");
 2775:         return 0;
 2776:     }
 2777:     #   Set up the hash as a database
 2778:     my %thesaurus_db;
 2779:     if (! tie(%thesaurus_db,'GDBM_File',
 2780:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2781:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2782:                                  $thesaurus_db_file);
 2783:         return 0;
 2784:     } 
 2785:     #  Get the average number of appearances of a word.
 2786:     my $avecount = $thesaurus_db{'average.count'};
 2787:     #  Put keywords (those that appear > average) into %Keywords
 2788:     while (my ($word,$data)=each (%thesaurus_db)) {
 2789:         my ($count,undef) = split /:/,$data;
 2790:         $Keywords{$word}++ if ($count > $avecount);
 2791:     }
 2792:     untie %thesaurus_db;
 2793:     # Remove special values from %Keywords.
 2794:     foreach my $value ('total.count','average.count') {
 2795:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2796:   }
 2797:     return 1;
 2798: }
 2799: 
 2800: ###################################################
 2801: 
 2802: =pod
 2803: 
 2804: =item * &keyword($word)
 2805: 
 2806: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2807: than the average number of times in the thesaurus database.  Calls 
 2808: &initialize_keywords
 2809: 
 2810: =cut
 2811: 
 2812: ###################################################
 2813: 
 2814: sub keyword {
 2815:     return if (!&initialize_keywords());
 2816:     my $word=lc(shift());
 2817:     $word=~s/\W//g;
 2818:     return exists($Keywords{$word});
 2819: }
 2820: 
 2821: ###############################################################
 2822: 
 2823: =pod 
 2824: 
 2825: =item * &get_related_words()
 2826: 
 2827: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2828: an array of words.  If the keyword is not in the thesaurus, an empty array
 2829: will be returned.  The order of the words returned is determined by the
 2830: database which holds them.
 2831: 
 2832: Uses global $thesaurus_db_file.
 2833: 
 2834: =cut
 2835: 
 2836: ###############################################################
 2837: sub get_related_words {
 2838:     my $keyword = shift;
 2839:     my %thesaurus_db;
 2840:     if (! -e $thesaurus_db_file) {
 2841:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2842:                                  "failed because the file does not exist");
 2843:         return ();
 2844:     }
 2845:     if (! tie(%thesaurus_db,'GDBM_File',
 2846:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2847:         return ();
 2848:     } 
 2849:     my @Words=();
 2850:     my $count=0;
 2851:     if (exists($thesaurus_db{$keyword})) {
 2852: 	# The first element is the number of times
 2853: 	# the word appears.  We do not need it now.
 2854: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2855: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2856: 	my $threshold=$mostfrequentcount/10;
 2857:         foreach my $possibleword (@RelatedWords) {
 2858:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2859:             if ($wordcount>$threshold) {
 2860: 		push(@Words,$word);
 2861:                 $count++;
 2862:                 if ($count>10) { last; }
 2863: 	    }
 2864:         }
 2865:     }
 2866:     untie %thesaurus_db;
 2867:     return @Words;
 2868: }
 2869: 
 2870: =pod
 2871: 
 2872: =back
 2873: 
 2874: =cut
 2875: 
 2876: # -------------------------------------------------------------- Plaintext name
 2877: =pod
 2878: 
 2879: =head1 User Name Functions
 2880: 
 2881: =over 4
 2882: 
 2883: =item * &plainname($uname,$udom,$first)
 2884: 
 2885: Takes a users logon name and returns it as a string in
 2886: "first middle last generation" form 
 2887: if $first is set to 'lastname' then it returns it as
 2888: 'lastname generation, firstname middlename' if their is a lastname
 2889: 
 2890: =cut
 2891: 
 2892: 
 2893: ###############################################################
 2894: sub plainname {
 2895:     my ($uname,$udom,$first)=@_;
 2896:     return if (!defined($uname) || !defined($udom));
 2897:     my %names=&getnames($uname,$udom);
 2898:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2899: 					  $names{'middlename'},
 2900: 					  $names{'lastname'},
 2901: 					  $names{'generation'},$first);
 2902:     $name=~s/^\s+//;
 2903:     $name=~s/\s+$//;
 2904:     $name=~s/\s+/ /g;
 2905:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2906:     return $name;
 2907: }
 2908: 
 2909: # -------------------------------------------------------------------- Nickname
 2910: =pod
 2911: 
 2912: =item * &nickname($uname,$udom)
 2913: 
 2914: Gets a users name and returns it as a string as
 2915: 
 2916: "&quot;nickname&quot;"
 2917: 
 2918: if the user has a nickname or
 2919: 
 2920: "first middle last generation"
 2921: 
 2922: if the user does not
 2923: 
 2924: =cut
 2925: 
 2926: sub nickname {
 2927:     my ($uname,$udom)=@_;
 2928:     return if (!defined($uname) || !defined($udom));
 2929:     my %names=&getnames($uname,$udom);
 2930:     my $name=$names{'nickname'};
 2931:     if ($name) {
 2932:        $name='&quot;'.$name.'&quot;'; 
 2933:     } else {
 2934:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2935: 	     $names{'lastname'}.' '.$names{'generation'};
 2936:        $name=~s/\s+$//;
 2937:        $name=~s/\s+/ /g;
 2938:     }
 2939:     return $name;
 2940: }
 2941: 
 2942: sub getnames {
 2943:     my ($uname,$udom)=@_;
 2944:     return if (!defined($uname) || !defined($udom));
 2945:     if ($udom eq 'public' && $uname eq 'public') {
 2946: 	return ('lastname' => &mt('Public'));
 2947:     }
 2948:     my $id=$uname.':'.$udom;
 2949:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2950:     if ($cached) {
 2951: 	return %{$names};
 2952:     } else {
 2953: 	my %loadnames=&Apache::lonnet::get('environment',
 2954:                     ['firstname','middlename','lastname','generation','nickname'],
 2955: 					 $udom,$uname);
 2956: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2957: 	return %loadnames;
 2958:     }
 2959: }
 2960: 
 2961: # -------------------------------------------------------------------- getemails
 2962: 
 2963: =pod
 2964: 
 2965: =item * &getemails($uname,$udom)
 2966: 
 2967: Gets a user's email information and returns it as a hash with keys:
 2968: notification, critnotification, permanentemail
 2969: 
 2970: For notification and critnotification, values are comma-separated lists 
 2971: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2972:  
 2973: 
 2974: =cut
 2975: 
 2976: 
 2977: sub getemails {
 2978:     my ($uname,$udom)=@_;
 2979:     if ($udom eq 'public' && $uname eq 'public') {
 2980: 	return;
 2981:     }
 2982:     if (!$udom) { $udom=$env{'user.domain'}; }
 2983:     if (!$uname) { $uname=$env{'user.name'}; }
 2984:     my $id=$uname.':'.$udom;
 2985:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2986:     if ($cached) {
 2987: 	return %{$names};
 2988:     } else {
 2989: 	my %loadnames=&Apache::lonnet::get('environment',
 2990:                     			   ['notification','critnotification',
 2991: 					    'permanentemail'],
 2992: 					   $udom,$uname);
 2993: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2994: 	return %loadnames;
 2995:     }
 2996: }
 2997: 
 2998: sub flush_email_cache {
 2999:     my ($uname,$udom)=@_;
 3000:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3001:     if (!$uname) { $uname=$env{'user.name'};   }
 3002:     return if ($udom eq 'public' && $uname eq 'public');
 3003:     my $id=$uname.':'.$udom;
 3004:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3005: }
 3006: 
 3007: # -------------------------------------------------------------------- getlangs
 3008: 
 3009: =pod
 3010: 
 3011: =item * &getlangs($uname,$udom)
 3012: 
 3013: Gets a user's language preference and returns it as a hash with key:
 3014: language.
 3015: 
 3016: =cut
 3017: 
 3018: 
 3019: sub getlangs {
 3020:     my ($uname,$udom) = @_;
 3021:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3022:     if (!$uname) { $uname=$env{'user.name'};   }
 3023:     my $id=$uname.':'.$udom;
 3024:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3025:     if ($cached) {
 3026:         return %{$langs};
 3027:     } else {
 3028:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3029:                                            $udom,$uname);
 3030:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3031:         return %loadlangs;
 3032:     }
 3033: }
 3034: 
 3035: sub flush_langs_cache {
 3036:     my ($uname,$udom)=@_;
 3037:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3038:     if (!$uname) { $uname=$env{'user.name'};   }
 3039:     return if ($udom eq 'public' && $uname eq 'public');
 3040:     my $id=$uname.':'.$udom;
 3041:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3042: }
 3043: 
 3044: # ------------------------------------------------------------------ Screenname
 3045: 
 3046: =pod
 3047: 
 3048: =item * &screenname($uname,$udom)
 3049: 
 3050: Gets a users screenname and returns it as a string
 3051: 
 3052: =cut
 3053: 
 3054: sub screenname {
 3055:     my ($uname,$udom)=@_;
 3056:     if ($uname eq $env{'user.name'} &&
 3057: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3058:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3059:     return $names{'screenname'};
 3060: }
 3061: 
 3062: 
 3063: # ------------------------------------------------------------- Confirm Wrapper
 3064: =pod
 3065: 
 3066: =item confirmwrapper
 3067: 
 3068: Wrap messages about completion of operation in box
 3069: 
 3070: =cut
 3071: 
 3072: sub confirmwrapper {
 3073:     my ($message)=@_;
 3074:     if ($message) {
 3075:         return "\n".'<div class="LC_confirm_box">'."\n"
 3076:                .$message."\n"
 3077:                .'</div>'."\n";
 3078:     } else {
 3079:         return $message;
 3080:     }
 3081: }
 3082: 
 3083: # ------------------------------------------------------------- Message Wrapper
 3084: 
 3085: sub messagewrapper {
 3086:     my ($link,$username,$domain,$subject,$text)=@_;
 3087:     return 
 3088:         '<a href="/adm/email?compose=individual&amp;'.
 3089:         'recname='.$username.'&amp;recdom='.$domain.
 3090: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3091:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3092: }
 3093: 
 3094: # --------------------------------------------------------------- Notes Wrapper
 3095: 
 3096: sub noteswrapper {
 3097:     my ($link,$un,$do)=@_;
 3098:     return 
 3099: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3100: }
 3101: 
 3102: # ------------------------------------------------------------- Aboutme Wrapper
 3103: 
 3104: sub aboutmewrapper {
 3105:     my ($link,$username,$domain,$target)=@_;
 3106:     if (!defined($username)  && !defined($domain)) {
 3107:         return;
 3108:     }
 3109:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3110: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3111: }
 3112: 
 3113: # ------------------------------------------------------------ Syllabus Wrapper
 3114: 
 3115: sub syllabuswrapper {
 3116:     my ($linktext,$coursedir,$domain)=@_;
 3117:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3118: }
 3119: 
 3120: # -----------------------------------------------------------------------------
 3121: 
 3122: sub track_student_link {
 3123:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3124:     my $link ="/adm/trackstudent?";
 3125:     my $title = 'View recent activity';
 3126:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3127:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3128:         $link .= "selected_student=$sname:$sdom";
 3129:         $title .= ' of this student';
 3130:     } 
 3131:     if (defined($target) && $target !~ /^\s*$/) {
 3132:         $target = qq{target="$target"};
 3133:     } else {
 3134:         $target = '';
 3135:     }
 3136:     if ($start) { $link.='&amp;start='.$start; }
 3137:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3138:     $title = &mt($title);
 3139:     $linktext = &mt($linktext);
 3140:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3141: 	&help_open_topic('View_recent_activity');
 3142: }
 3143: 
 3144: sub slot_reservations_link {
 3145:     my ($linktext,$sname,$sdom,$target) = @_;
 3146:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3147:     my $title = 'View slot reservation history';
 3148:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3149:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3150:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3151:         $title .= ' of this student';
 3152:     }
 3153:     if (defined($target) && $target !~ /^\s*$/) {
 3154:         $target = qq{target="$target"};
 3155:     } else {
 3156:         $target = '';
 3157:     }
 3158:     $title = &mt($title);
 3159:     $linktext = &mt($linktext);
 3160:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3161: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3162: 
 3163: }
 3164: 
 3165: # ===================================================== Display a student photo
 3166: 
 3167: 
 3168: sub student_image_tag {
 3169:     my ($domain,$user)=@_;
 3170:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3171:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3172: 	return '<img src="'.$imgsrc.'" align="right" />';
 3173:     } else {
 3174: 	return '';
 3175:     }
 3176: }
 3177: 
 3178: =pod
 3179: 
 3180: =back
 3181: 
 3182: =head1 Access .tab File Data
 3183: 
 3184: =over 4
 3185: 
 3186: =item * &languageids() 
 3187: 
 3188: returns list of all language ids
 3189: 
 3190: =cut
 3191: 
 3192: sub languageids {
 3193:     return sort(keys(%language));
 3194: }
 3195: 
 3196: =pod
 3197: 
 3198: =item * &languagedescription() 
 3199: 
 3200: returns description of a specified language id
 3201: 
 3202: =cut
 3203: 
 3204: sub languagedescription {
 3205:     my $code=shift;
 3206:     return  ($supported_language{$code}?'* ':'').
 3207:             $language{$code}.
 3208: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3209: }
 3210: 
 3211: sub plainlanguagedescription {
 3212:     my $code=shift;
 3213:     return $language{$code};
 3214: }
 3215: 
 3216: sub supportedlanguagecode {
 3217:     my $code=shift;
 3218:     return $supported_language{$code};
 3219: }
 3220: 
 3221: =pod
 3222: 
 3223: =item * &copyrightids() 
 3224: 
 3225: returns list of all copyrights
 3226: 
 3227: =cut
 3228: 
 3229: sub copyrightids {
 3230:     return sort(keys(%cprtag));
 3231: }
 3232: 
 3233: =pod
 3234: 
 3235: =item * &copyrightdescription() 
 3236: 
 3237: returns description of a specified copyright id
 3238: 
 3239: =cut
 3240: 
 3241: sub copyrightdescription {
 3242:     return &mt($cprtag{shift(@_)});
 3243: }
 3244: 
 3245: =pod
 3246: 
 3247: =item * &source_copyrightids() 
 3248: 
 3249: returns list of all source copyrights
 3250: 
 3251: =cut
 3252: 
 3253: sub source_copyrightids {
 3254:     return sort(keys(%scprtag));
 3255: }
 3256: 
 3257: =pod
 3258: 
 3259: =item * &source_copyrightdescription() 
 3260: 
 3261: returns description of a specified source copyright id
 3262: 
 3263: =cut
 3264: 
 3265: sub source_copyrightdescription {
 3266:     return &mt($scprtag{shift(@_)});
 3267: }
 3268: 
 3269: =pod
 3270: 
 3271: =item * &filecategories() 
 3272: 
 3273: returns list of all file categories
 3274: 
 3275: =cut
 3276: 
 3277: sub filecategories {
 3278:     return sort(keys(%category_extensions));
 3279: }
 3280: 
 3281: =pod
 3282: 
 3283: =item * &filecategorytypes() 
 3284: 
 3285: returns list of file types belonging to a given file
 3286: category
 3287: 
 3288: =cut
 3289: 
 3290: sub filecategorytypes {
 3291:     my ($cat) = @_;
 3292:     return @{$category_extensions{lc($cat)}};
 3293: }
 3294: 
 3295: =pod
 3296: 
 3297: =item * &fileembstyle() 
 3298: 
 3299: returns embedding style for a specified file type
 3300: 
 3301: =cut
 3302: 
 3303: sub fileembstyle {
 3304:     return $fe{lc(shift(@_))};
 3305: }
 3306: 
 3307: sub filemimetype {
 3308:     return $fm{lc(shift(@_))};
 3309: }
 3310: 
 3311: 
 3312: sub filecategoryselect {
 3313:     my ($name,$value)=@_;
 3314:     return &select_form($value,$name,
 3315: 			{'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3316: }
 3317: 
 3318: =pod
 3319: 
 3320: =item * &filedescription() 
 3321: 
 3322: returns description for a specified file type
 3323: 
 3324: =cut
 3325: 
 3326: sub filedescription {
 3327:     my $file_description = $fd{lc(shift())};
 3328:     $file_description =~ s:([\[\]]):~$1:g;
 3329:     return &mt($file_description);
 3330: }
 3331: 
 3332: =pod
 3333: 
 3334: =item * &filedescriptionex() 
 3335: 
 3336: returns description for a specified file type with
 3337: extra formatting
 3338: 
 3339: =cut
 3340: 
 3341: sub filedescriptionex {
 3342:     my $ex=shift;
 3343:     my $file_description = $fd{lc($ex)};
 3344:     $file_description =~ s:([\[\]]):~$1:g;
 3345:     return '.'.$ex.' '.&mt($file_description);
 3346: }
 3347: 
 3348: # End of .tab access
 3349: =pod
 3350: 
 3351: =back
 3352: 
 3353: =cut
 3354: 
 3355: # ------------------------------------------------------------------ File Types
 3356: sub fileextensions {
 3357:     return sort(keys(%fe));
 3358: }
 3359: 
 3360: # ----------------------------------------------------------- Display Languages
 3361: # returns a hash with all desired display languages
 3362: #
 3363: 
 3364: sub display_languages {
 3365:     my %languages=();
 3366:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3367: 	$languages{$lang}=1;
 3368:     }
 3369:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3370:     if ($env{'form.displaylanguage'}) {
 3371: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3372: 	    $languages{$lang}=1;
 3373:         }
 3374:     }
 3375:     return %languages;
 3376: }
 3377: 
 3378: sub languages {
 3379:     my ($possible_langs) = @_;
 3380:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3381:     if (!ref($possible_langs)) {
 3382: 	if( wantarray ) {
 3383: 	    return @preferred_langs;
 3384: 	} else {
 3385: 	    return $preferred_langs[0];
 3386: 	}
 3387:     }
 3388:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3389:     my @preferred_possibilities;
 3390:     foreach my $preferred_lang (@preferred_langs) {
 3391: 	if (exists($possibilities{$preferred_lang})) {
 3392: 	    push(@preferred_possibilities, $preferred_lang);
 3393: 	}
 3394:     }
 3395:     if( wantarray ) {
 3396: 	return @preferred_possibilities;
 3397:     }
 3398:     return $preferred_possibilities[0];
 3399: }
 3400: 
 3401: sub user_lang {
 3402:     my ($touname,$toudom,$fromcid) = @_;
 3403:     my @userlangs;
 3404:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3405:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3406:                     $env{'course.'.$fromcid.'.languages'}));
 3407:     } else {
 3408:         my %langhash = &getlangs($touname,$toudom);
 3409:         if ($langhash{'languages'} ne '') {
 3410:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3411:         } else {
 3412:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3413:             if ($domdefs{'lang_def'} ne '') {
 3414:                 @userlangs = ($domdefs{'lang_def'});
 3415:             }
 3416:         }
 3417:     }
 3418:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3419:     my $user_lh = Apache::localize->get_handle(@languages);
 3420:     return $user_lh;
 3421: }
 3422: 
 3423: 
 3424: ###############################################################
 3425: ##               Student Answer Attempts                     ##
 3426: ###############################################################
 3427: 
 3428: =pod
 3429: 
 3430: =head1 Alternate Problem Views
 3431: 
 3432: =over 4
 3433: 
 3434: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3435:     $getattempt, $regexp, $gradesub)
 3436: 
 3437: Return string with previous attempt on problem. Arguments:
 3438: 
 3439: =over 4
 3440: 
 3441: =item * $symb: Problem, including path
 3442: 
 3443: =item * $username: username of the desired student
 3444: 
 3445: =item * $domain: domain of the desired student
 3446: 
 3447: =item * $course: Course ID
 3448: 
 3449: =item * $getattempt: Leave blank for all attempts, otherwise put
 3450:     something
 3451: 
 3452: =item * $regexp: if string matches this regexp, the string will be
 3453:     sent to $gradesub
 3454: 
 3455: =item * $gradesub: routine that processes the string if it matches $regexp
 3456: 
 3457: =back
 3458: 
 3459: The output string is a table containing all desired attempts, if any.
 3460: 
 3461: =cut
 3462: 
 3463: sub get_previous_attempt {
 3464:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3465:   my $prevattempts='';
 3466:   no strict 'refs';
 3467:   if ($symb) {
 3468:     my (%returnhash)=
 3469:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3470:     if ($returnhash{'version'}) {
 3471:       my %lasthash=();
 3472:       my $version;
 3473:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3474:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3475: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3476:         }
 3477:       }
 3478:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3479:       $prevattempts.='<th>'.&mt('History').'</th>';
 3480:       my (%typeparts,%lasthidden);
 3481:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3482:       foreach my $key (sort(keys(%lasthash))) {
 3483: 	my ($ign,@parts) = split(/\./,$key);
 3484: 	if ($#parts > 0) {
 3485: 	  my $data=$parts[-1];
 3486:           next if ($data eq 'foilorder');
 3487: 	  pop(@parts);
 3488:           if ($data eq 'type') {
 3489:               unless ($showsurv) {
 3490:                   my $id = join(',',@parts);
 3491:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3492:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3493:                       $lasthidden{$ign.'.'.$id} = 1;
 3494:                   }
 3495:               }
 3496:               delete($lasthash{$key});
 3497:           } else {
 3498: 	      $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3499:           }
 3500: 	} else {
 3501: 	  if ($#parts == 0) {
 3502: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3503: 	  } else {
 3504: 	    $prevattempts.='<th>'.$ign.'</th>';
 3505: 	  }
 3506: 	}
 3507:       }
 3508:       $prevattempts.=&end_data_table_header_row();
 3509:       if ($getattempt eq '') {
 3510: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3511:             my @hidden;
 3512:             if (%typeparts) {
 3513:                 foreach my $id (keys(%typeparts)) {
 3514:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3515:                         push(@hidden,$id);
 3516:                     }
 3517:                 }
 3518:             }
 3519:             $prevattempts.=&start_data_table_row().
 3520:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3521:             if (@hidden) {
 3522:                 foreach my $key (sort(keys(%lasthash))) {
 3523:                     next if ($key =~ /\.foilorder$/);
 3524:                     my $hide;
 3525:                     foreach my $id (@hidden) {
 3526:                         if ($key =~ /^\Q$id\E/) {
 3527:                             $hide = 1;
 3528:                             last;
 3529:                         }
 3530:                     }
 3531:                     if ($hide) {
 3532:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3533:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3534:                             my $value = &format_previous_attempt_value($key,
 3535:                                              $returnhash{$version.':'.$key});
 3536:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3537:                         } else {
 3538:                             $prevattempts.='<td>&nbsp;</td>';
 3539:                         }
 3540:                     } else {
 3541:                         if ($key =~ /\./) {
 3542:                             my $value = &format_previous_attempt_value($key,
 3543:                                               $returnhash{$version.':'.$key});
 3544:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3545:                         } else {
 3546:                             $prevattempts.='<td>&nbsp;</td>';
 3547:                         }
 3548:                     }
 3549:                 }
 3550:             } else {
 3551: 	        foreach my $key (sort(keys(%lasthash))) {
 3552:                     next if ($key =~ /\.foilorder$/);
 3553: 		    my $value = &format_previous_attempt_value($key,
 3554: 			            $returnhash{$version.':'.$key});
 3555: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3556: 	        }
 3557:             }
 3558: 	    $prevattempts.=&end_data_table_row();
 3559: 	 }
 3560:       }
 3561:       my @currhidden = keys(%lasthidden);
 3562:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3563:       foreach my $key (sort(keys(%lasthash))) {
 3564:           next if ($key =~ /\.foilorder$/);
 3565:           if (%typeparts) {
 3566:               my $hidden;
 3567:               foreach my $id (@currhidden) {
 3568:                   if ($key =~ /^\Q$id\E/) {
 3569:                       $hidden = 1;
 3570:                       last;
 3571:                   }
 3572:               }
 3573:               if ($hidden) {
 3574:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3575:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3576:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3577:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3578:                           $value = &$gradesub($value);
 3579:                       }
 3580:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3581:                   } else {
 3582:                       $prevattempts.='<td>&nbsp;</td>';
 3583:                   }
 3584:               } else {
 3585:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3586:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3587:                       $value = &$gradesub($value);
 3588:                   }
 3589:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3590:               }
 3591:           } else {
 3592: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3593: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3594:                   $value = &$gradesub($value);
 3595:               }
 3596: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3597:           }
 3598:       }
 3599:       $prevattempts.= &end_data_table_row().&end_data_table();
 3600:     } else {
 3601:       $prevattempts=
 3602: 	  &start_data_table().&start_data_table_row().
 3603: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3604: 	  &end_data_table_row().&end_data_table();
 3605:     }
 3606:   } else {
 3607:     $prevattempts=
 3608: 	  &start_data_table().&start_data_table_row().
 3609: 	  '<td>'.&mt('No data.').'</td>'.
 3610: 	  &end_data_table_row().&end_data_table();
 3611:   }
 3612: }
 3613: 
 3614: sub format_previous_attempt_value {
 3615:     my ($key,$value) = @_;
 3616:     if ($key =~ /timestamp/) {
 3617: 	$value = &Apache::lonlocal::locallocaltime($value);
 3618:     } elsif (ref($value) eq 'ARRAY') {
 3619: 	$value = '('.join(', ', @{ $value }).')';
 3620:     } elsif ($key =~ /answerstring$/) {
 3621:         my %answers = &Apache::lonnet::str2hash($value);
 3622:         my @anskeys = sort(keys(%answers));
 3623:         if (@anskeys == 1) {
 3624:             my $answer = $answers{$anskeys[0]};
 3625:             if ($answer =~ m{\0}) {
 3626:                 $answer =~ s{\0}{,}g;
 3627:             }
 3628:             my $tag_internal_answer_name = 'INTERNAL';
 3629:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3630:                 $value = $answer;
 3631:             } else {
 3632:                 $value = $anskeys[0].'='.$answer;
 3633:             }
 3634:         } else {
 3635:             foreach my $ans (@anskeys) {
 3636:                 my $answer = $answers{$ans};
 3637:                 if ($answer =~ m{\0}) {
 3638:                     $answer =~ s{\0}{,}g;
 3639:                 }
 3640:                 $value .=  $ans.'='.$answer.'<br />';;
 3641:             }
 3642:         }
 3643:     } else {
 3644: 	$value = &unescape($value);
 3645:     }
 3646:     return $value;
 3647: }
 3648: 
 3649: 
 3650: sub relative_to_absolute {
 3651:     my ($url,$output)=@_;
 3652:     my $parser=HTML::TokeParser->new(\$output);
 3653:     my $token;
 3654:     my $thisdir=$url;
 3655:     my @rlinks=();
 3656:     while ($token=$parser->get_token) {
 3657: 	if ($token->[0] eq 'S') {
 3658: 	    if ($token->[1] eq 'a') {
 3659: 		if ($token->[2]->{'href'}) {
 3660: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3661: 		}
 3662: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3663: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3664: 	    } elsif ($token->[1] eq 'base') {
 3665: 		$thisdir=$token->[2]->{'href'};
 3666: 	    }
 3667: 	}
 3668:     }
 3669:     $thisdir=~s-/[^/]*$--;
 3670:     foreach my $link (@rlinks) {
 3671: 	unless (($link=~/^https?\:\/\//i) ||
 3672: 		($link=~/^\//) ||
 3673: 		($link=~/^javascript:/i) ||
 3674: 		($link=~/^mailto:/i) ||
 3675: 		($link=~/^\#/)) {
 3676: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3677: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3678: 	}
 3679:     }
 3680: # -------------------------------------------------- Deal with Applet codebases
 3681:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3682:     return $output;
 3683: }
 3684: 
 3685: =pod
 3686: 
 3687: =item * &get_student_view()
 3688: 
 3689: show a snapshot of what student was looking at
 3690: 
 3691: =cut
 3692: 
 3693: sub get_student_view {
 3694:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3695:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3696:   my (%form);
 3697:   my @elements=('symb','courseid','domain','username');
 3698:   foreach my $element (@elements) {
 3699:       $form{'grade_'.$element}=eval '$'.$element #'
 3700:   }
 3701:   if (defined($moreenv)) {
 3702:       %form=(%form,%{$moreenv});
 3703:   }
 3704:   if (defined($target)) { $form{'grade_target'} = $target; }
 3705:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3706:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3707:   $userview=~s/\<body[^\>]*\>//gi;
 3708:   $userview=~s/\<\/body\>//gi;
 3709:   $userview=~s/\<html\>//gi;
 3710:   $userview=~s/\<\/html\>//gi;
 3711:   $userview=~s/\<head\>//gi;
 3712:   $userview=~s/\<\/head\>//gi;
 3713:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3714:   $userview=&relative_to_absolute($feedurl,$userview);
 3715:   if (wantarray) {
 3716:      return ($userview,$response);
 3717:   } else {
 3718:      return $userview;
 3719:   }
 3720: }
 3721: 
 3722: sub get_student_view_with_retries {
 3723:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3724: 
 3725:     my $ok = 0;                 # True if we got a good response.
 3726:     my $content;
 3727:     my $response;
 3728: 
 3729:     # Try to get the student_view done. within the retries count:
 3730:     
 3731:     do {
 3732:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3733:          $ok      = $response->is_success;
 3734:          if (!$ok) {
 3735:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3736:          }
 3737:          $retries--;
 3738:     } while (!$ok && ($retries > 0));
 3739:     
 3740:     if (!$ok) {
 3741:        $content = '';          # On error return an empty content.
 3742:     }
 3743:     if (wantarray) {
 3744:        return ($content, $response);
 3745:     } else {
 3746:        return $content;
 3747:     }
 3748: }
 3749: 
 3750: =pod
 3751: 
 3752: =item * &get_student_answers() 
 3753: 
 3754: show a snapshot of how student was answering problem
 3755: 
 3756: =cut
 3757: 
 3758: sub get_student_answers {
 3759:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3760:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3761:   my (%moreenv);
 3762:   my @elements=('symb','courseid','domain','username');
 3763:   foreach my $element (@elements) {
 3764:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3765:   }
 3766:   $moreenv{'grade_target'}='answer';
 3767:   %moreenv=(%form,%moreenv);
 3768:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3769:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3770:   return $userview;
 3771: }
 3772: 
 3773: =pod
 3774: 
 3775: =item * &submlink()
 3776: 
 3777: Inputs: $text $uname $udom $symb $target
 3778: 
 3779: Returns: A link to grades.pm such as to see the SUBM view of a student
 3780: 
 3781: =cut
 3782: 
 3783: ###############################################
 3784: sub submlink {
 3785:     my ($text,$uname,$udom,$symb,$target)=@_;
 3786:     if (!($uname && $udom)) {
 3787: 	(my $cursymb, my $courseid,$udom,$uname)=
 3788: 	    &Apache::lonnet::whichuser($symb);
 3789: 	if (!$symb) { $symb=$cursymb; }
 3790:     }
 3791:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3792:     $symb=&escape($symb);
 3793:     if ($target) { $target=" target=\"$target\""; }
 3794:     return
 3795:         '<a href="/adm/grades?command=submission'.
 3796:         '&amp;symb='.$symb.
 3797:         '&amp;student='.$uname.
 3798:         '&amp;userdom='.$udom.'"'.
 3799:         $target.'>'.$text.'</a>';
 3800: }
 3801: ##############################################
 3802: 
 3803: =pod
 3804: 
 3805: =item * &pgrdlink()
 3806: 
 3807: Inputs: $text $uname $udom $symb $target
 3808: 
 3809: Returns: A link to grades.pm such as to see the PGRD view of a student
 3810: 
 3811: =cut
 3812: 
 3813: ###############################################
 3814: sub pgrdlink {
 3815:     my $link=&submlink(@_);
 3816:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3817:     return $link;
 3818: }
 3819: ##############################################
 3820: 
 3821: =pod
 3822: 
 3823: =item * &pprmlink()
 3824: 
 3825: Inputs: $text $uname $udom $symb $target
 3826: 
 3827: Returns: A link to parmset.pm such as to see the PPRM view of a
 3828: student and a specific resource
 3829: 
 3830: =cut
 3831: 
 3832: ###############################################
 3833: sub pprmlink {
 3834:     my ($text,$uname,$udom,$symb,$target)=@_;
 3835:     if (!($uname && $udom)) {
 3836: 	(my $cursymb, my $courseid,$udom,$uname)=
 3837: 	    &Apache::lonnet::whichuser($symb);
 3838: 	if (!$symb) { $symb=$cursymb; }
 3839:     }
 3840:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3841:     $symb=&escape($symb);
 3842:     if ($target) { $target="target=\"$target\""; }
 3843:     return '<a href="/adm/parmset?command=set&amp;'.
 3844: 	'symb='.$symb.'&amp;uname='.$uname.
 3845: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3846: }
 3847: ##############################################
 3848: 
 3849: =pod
 3850: 
 3851: =back
 3852: 
 3853: =cut
 3854: 
 3855: ###############################################
 3856: 
 3857: 
 3858: sub timehash {
 3859:     my ($thistime) = @_;
 3860:     my $timezone = &Apache::lonlocal::gettimezone();
 3861:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3862:                      ->set_time_zone($timezone);
 3863:     my $wday = $dt->day_of_week();
 3864:     if ($wday == 7) { $wday = 0; }
 3865:     return ( 'second' => $dt->second(),
 3866:              'minute' => $dt->minute(),
 3867:              'hour'   => $dt->hour(),
 3868:              'day'     => $dt->day_of_month(),
 3869:              'month'   => $dt->month(),
 3870:              'year'    => $dt->year(),
 3871:              'weekday' => $wday,
 3872:              'dayyear' => $dt->day_of_year(),
 3873:              'dlsav'   => $dt->is_dst() );
 3874: }
 3875: 
 3876: sub utc_string {
 3877:     my ($date)=@_;
 3878:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3879: }
 3880: 
 3881: sub maketime {
 3882:     my %th=@_;
 3883:     my ($epoch_time,$timezone,$dt);
 3884:     $timezone = &Apache::lonlocal::gettimezone();
 3885:     eval {
 3886:         $dt = DateTime->new( year   => $th{'year'},
 3887:                              month  => $th{'month'},
 3888:                              day    => $th{'day'},
 3889:                              hour   => $th{'hour'},
 3890:                              minute => $th{'minute'},
 3891:                              second => $th{'second'},
 3892:                              time_zone => $timezone,
 3893:                          );
 3894:     };
 3895:     if (!$@) {
 3896:         $epoch_time = $dt->epoch;
 3897:         if ($epoch_time) {
 3898:             return $epoch_time;
 3899:         }
 3900:     }
 3901:     return POSIX::mktime(
 3902:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3903:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3904: }
 3905: 
 3906: #########################################
 3907: 
 3908: sub findallcourses {
 3909:     my ($roles,$uname,$udom) = @_;
 3910:     my %roles;
 3911:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3912:     my %courses;
 3913:     my $now=time;
 3914:     if (!defined($uname)) {
 3915:         $uname = $env{'user.name'};
 3916:     }
 3917:     if (!defined($udom)) {
 3918:         $udom = $env{'user.domain'};
 3919:     }
 3920:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3921:         my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 3922:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
 3923:                                               $extra);
 3924:         if (!%roles) {
 3925:             %roles = (
 3926:                        cc => 1,
 3927:                        co => 1,
 3928:                        in => 1,
 3929:                        ep => 1,
 3930:                        ta => 1,
 3931:                        cr => 1,
 3932:                        st => 1,
 3933:              );
 3934:         }
 3935:         foreach my $entry (keys(%roleshash)) {
 3936:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3937:             if ($trole =~ /^cr/) { 
 3938:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3939:             } else {
 3940:                 next if (!exists($roles{$trole}));
 3941:             }
 3942:             if ($tend) {
 3943:                 next if ($tend < $now);
 3944:             }
 3945:             if ($tstart) {
 3946:                 next if ($tstart > $now);
 3947:             }
 3948:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3949:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3950:             if ($secpart eq '') {
 3951:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3952:                 $sec = 'none';
 3953:                 $realsec = '';
 3954:             } else {
 3955:                 $cnum = $cnumpart;
 3956:                 ($sec,$role) = split(/_/,$secpart);
 3957:                 $realsec = $sec;
 3958:             }
 3959:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3960:         }
 3961:     } else {
 3962:         foreach my $key (keys(%env)) {
 3963: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3964:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3965: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3966: 	        next if ($role eq 'ca' || $role eq 'aa');
 3967: 	        next if (%roles && !exists($roles{$role}));
 3968: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3969:                 my $active=1;
 3970:                 if ($starttime) {
 3971: 		    if ($now<$starttime) { $active=0; }
 3972:                 }
 3973:                 if ($endtime) {
 3974:                     if ($now>$endtime) { $active=0; }
 3975:                 }
 3976:                 if ($active) {
 3977:                     if ($sec eq '') {
 3978:                         $sec = 'none';
 3979:                     }
 3980:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3981:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3982:                 }
 3983:             }
 3984:         }
 3985:     }
 3986:     return %courses;
 3987: }
 3988: 
 3989: ###############################################
 3990: 
 3991: sub blockcheck {
 3992:     my ($setters,$activity,$uname,$udom) = @_;
 3993: 
 3994:     if (!defined($udom)) {
 3995:         $udom = $env{'user.domain'};
 3996:     }
 3997:     if (!defined($uname)) {
 3998:         $uname = $env{'user.name'};
 3999:     }
 4000: 
 4001:     # If uname and udom are for a course, check for blocks in the course.
 4002: 
 4003:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4004:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 4005:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 4006:         return ($startblock,$endblock);
 4007:     }
 4008: 
 4009:     my $startblock = 0;
 4010:     my $endblock = 0;
 4011:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4012: 
 4013:     # If uname is for a user, and activity is course-specific, i.e.,
 4014:     # boards, chat or groups, check for blocking in current course only.
 4015: 
 4016:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4017:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4018:         foreach my $key (keys(%live_courses)) {
 4019:             if ($key ne $env{'request.course.id'}) {
 4020:                 delete($live_courses{$key});
 4021:             }
 4022:         }
 4023:     }
 4024: 
 4025:     my $otheruser = 0;
 4026:     my %own_courses;
 4027:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4028:         # Resource belongs to user other than current user.
 4029:         $otheruser = 1;
 4030:         # Gather courses for current user
 4031:         %own_courses = 
 4032:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4033:     }
 4034: 
 4035:     # Gather active course roles - course coordinator, instructor, 
 4036:     # exam proctor, ta, student, or custom role.
 4037: 
 4038:     foreach my $course (keys(%live_courses)) {
 4039:         my ($cdom,$cnum);
 4040:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4041:             $cdom = $env{'course.'.$course.'.domain'};
 4042:             $cnum = $env{'course.'.$course.'.num'};
 4043:         } else {
 4044:             ($cdom,$cnum) = split(/_/,$course); 
 4045:         }
 4046:         my $no_ownblock = 0;
 4047:         my $no_userblock = 0;
 4048:         if ($otheruser && $activity ne 'com') {
 4049:             # Check if current user has 'evb' priv for this
 4050:             if (defined($own_courses{$course})) {
 4051:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4052:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4053:                     if ($sec ne 'none') {
 4054:                         $checkrole .= '/'.$sec;
 4055:                     }
 4056:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4057:                         $no_ownblock = 1;
 4058:                         last;
 4059:                     }
 4060:                 }
 4061:             }
 4062:             # if they have 'evb' priv and are currently not playing student
 4063:             next if (($no_ownblock) &&
 4064:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4065:         }
 4066:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4067:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4068:             if ($sec ne 'none') {
 4069:                 $checkrole .= '/'.$sec;
 4070:             }
 4071:             if ($otheruser) {
 4072:                 # Resource belongs to user other than current user.
 4073:                 # Assemble privs for that user, and check for 'evb' priv.
 4074:                 my ($trole,$tdom,$tnum,$tsec);
 4075:                 my $entry = $live_courses{$course}{$sec};
 4076:                 if ($entry =~ /^cr/) {
 4077:                     ($trole,$tdom,$tnum,$tsec) = 
 4078:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4079:                 } else {
 4080:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4081:                 }
 4082:                 my ($spec,$area,$trest,%allroles,%userroles);
 4083:                 $area = '/'.$tdom.'/'.$tnum;
 4084:                 $trest = $tnum;
 4085:                 if ($tsec ne '') {
 4086:                     $area .= '/'.$tsec;
 4087:                     $trest .= '/'.$tsec;
 4088:                 }
 4089:                 $spec = $trole.'.'.$area;
 4090:                 if ($trole =~ /^cr/) {
 4091:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4092:                                                       $tdom,$spec,$trest,$area);
 4093:                 } else {
 4094:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4095:                                                        $tdom,$spec,$trest,$area);
 4096:                 }
 4097:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4098:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4099:                     if ($1) {
 4100:                         $no_userblock = 1;
 4101:                         last;
 4102:                     }
 4103:                 }
 4104:             } else {
 4105:                 # Resource belongs to current user
 4106:                 # Check for 'evb' priv via lonnet::allowed().
 4107:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4108:                     $no_ownblock = 1;
 4109:                     last;
 4110:                 }
 4111:             }
 4112:         }
 4113:         # if they have the evb priv and are currently not playing student
 4114:         next if (($no_ownblock) &&
 4115:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4116:         next if ($no_userblock);
 4117: 
 4118:         # Retrieve blocking times and identity of locker for course
 4119:         # of specified user, unless user has 'evb' privilege.
 4120:         
 4121:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4122:         if (($start != 0) && 
 4123:             (($startblock == 0) || ($startblock > $start))) {
 4124:             $startblock = $start;
 4125:         }
 4126:         if (($end != 0)  &&
 4127:             (($endblock == 0) || ($endblock < $end))) {
 4128:             $endblock = $end;
 4129:         }
 4130:     }
 4131:     return ($startblock,$endblock);
 4132: }
 4133: 
 4134: sub get_blocks {
 4135:     my ($setters,$activity,$cdom,$cnum) = @_;
 4136:     my $startblock = 0;
 4137:     my $endblock = 0;
 4138:     my $course = $cdom.'_'.$cnum;
 4139:     $setters->{$course} = {};
 4140:     $setters->{$course}{'staff'} = [];
 4141:     $setters->{$course}{'times'} = [];
 4142:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4143:     foreach my $record (keys(%records)) {
 4144:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4145:         if ($start <= time && $end >= time) {
 4146:             my ($staff_name,$staff_dom,$title,$blocks) =
 4147:                 &parse_block_record($records{$record});
 4148:             if ($blocks->{$activity} eq 'on') {
 4149:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4150:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4151:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4152:                     $startblock = $start;
 4153:                 }
 4154:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4155:                     $endblock = $end;
 4156:                 }
 4157:             }
 4158:         }
 4159:     }
 4160:     return ($startblock,$endblock);
 4161: }
 4162: 
 4163: sub parse_block_record {
 4164:     my ($record) = @_;
 4165:     my ($setuname,$setudom,$title,$blocks);
 4166:     if (ref($record) eq 'HASH') {
 4167:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4168:         $title = &unescape($record->{'event'});
 4169:         $blocks = $record->{'blocks'};
 4170:     } else {
 4171:         my @data = split(/:/,$record,3);
 4172:         if (scalar(@data) eq 2) {
 4173:             $title = $data[1];
 4174:             ($setuname,$setudom) = split(/@/,$data[0]);
 4175:         } else {
 4176:             ($setuname,$setudom,$title) = @data;
 4177:         }
 4178:         $blocks = { 'com' => 'on' };
 4179:     }
 4180:     return ($setuname,$setudom,$title,$blocks);
 4181: }
 4182: 
 4183: sub blocking_status {
 4184:   my ($activity,$uname,$udom) = @_;
 4185:   my %setters;
 4186: 
 4187:   # check for active blocking
 4188:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4189: 
 4190:   my $blocked = $startblock && $endblock ? 1 : 0;
 4191: 
 4192:   # caller just wants to know whether a block is active
 4193:   if (!wantarray) { return $blocked; }
 4194: 
 4195:   # build a link to a popup window containing the details
 4196:   my $querystring  = "?activity=$activity";
 4197:   # $uname and $udom decide whose portfolio the user is trying to look at
 4198:      $querystring .= "&amp;udom=$udom"      if $udom;
 4199:      $querystring .= "&amp;uname=$uname"    if $uname;
 4200: 
 4201:   my $output .= <<'END_MYBLOCK';
 4202:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4203:         var options = "width=" + w + ",height=" + h + ",";
 4204:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4205:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4206:         var newWin = window.open(url, wdwName, options);
 4207:         newWin.focus();
 4208:     }
 4209: END_MYBLOCK
 4210: 
 4211:   $output = Apache::lonhtmlcommon::scripttag($output);
 4212:   
 4213:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4214:   my $text = mt('Communication Blocked');
 4215: 
 4216:   $output .= <<"END_BLOCK";
 4217: <div class='LC_comblock'>
 4218:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4219:   title='$text'>
 4220:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4221:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4222:   title='$text'>$text</a>
 4223: </div>
 4224: 
 4225: END_BLOCK
 4226: 
 4227:   return ($blocked, $output);
 4228: }
 4229: 
 4230: ###############################################
 4231: 
 4232: sub check_ip_acc {
 4233:     my ($acc)=@_;
 4234:     &Apache::lonxml::debug("acc is $acc");
 4235:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4236:         return 1;
 4237:     }
 4238:     my $allowed=0;
 4239:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4240: 
 4241:     my $name;
 4242:     foreach my $pattern (split(',',$acc)) {
 4243:         $pattern =~ s/^\s*//;
 4244:         $pattern =~ s/\s*$//;
 4245:         if ($pattern =~ /\*$/) {
 4246:             #35.8.*
 4247:             $pattern=~s/\*//;
 4248:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4249:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4250:             #35.8.3.[34-56]
 4251:             my $low=$2;
 4252:             my $high=$3;
 4253:             $pattern=$1;
 4254:             if ($ip =~ /^\Q$pattern\E/) {
 4255:                 my $last=(split(/\./,$ip))[3];
 4256:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4257:             }
 4258:         } elsif ($pattern =~ /^\*/) {
 4259:             #*.msu.edu
 4260:             $pattern=~s/\*//;
 4261:             if (!defined($name)) {
 4262:                 use Socket;
 4263:                 my $netaddr=inet_aton($ip);
 4264:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4265:             }
 4266:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4267:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4268:             #127.0.0.1
 4269:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4270:         } else {
 4271:             #some.name.com
 4272:             if (!defined($name)) {
 4273:                 use Socket;
 4274:                 my $netaddr=inet_aton($ip);
 4275:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4276:             }
 4277:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4278:         }
 4279:         if ($allowed) { last; }
 4280:     }
 4281:     return $allowed;
 4282: }
 4283: 
 4284: ###############################################
 4285: 
 4286: =pod
 4287: 
 4288: =head1 Domain Template Functions
 4289: 
 4290: =over 4
 4291: 
 4292: =item * &determinedomain()
 4293: 
 4294: Inputs: $domain (usually will be undef)
 4295: 
 4296: Returns: Determines which domain should be used for designs
 4297: 
 4298: =cut
 4299: 
 4300: ###############################################
 4301: sub determinedomain {
 4302:     my $domain=shift;
 4303:     if (! $domain) {
 4304:         # Determine domain if we have not been given one
 4305:         $domain = &Apache::lonnet::default_login_domain();
 4306:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4307:         if ($env{'request.role.domain'}) { 
 4308:             $domain=$env{'request.role.domain'}; 
 4309:         }
 4310:     }
 4311:     return $domain;
 4312: }
 4313: ###############################################
 4314: 
 4315: sub devalidate_domconfig_cache {
 4316:     my ($udom)=@_;
 4317:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4318: }
 4319: 
 4320: # ---------------------- Get domain configuration for a domain
 4321: sub get_domainconf {
 4322:     my ($udom) = @_;
 4323:     my $cachetime=1800;
 4324:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4325:     if (defined($cached)) { return %{$result}; }
 4326: 
 4327:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4328: 					     ['login','rolecolors','autoenroll'],$udom);
 4329:     my (%designhash,%legacy);
 4330:     if (keys(%domconfig) > 0) {
 4331:         if (ref($domconfig{'login'}) eq 'HASH') {
 4332:             if (keys(%{$domconfig{'login'}})) {
 4333:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4334:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4335:                         if ($key eq 'loginvia') {
 4336:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4337:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4338:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4339:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4340:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4341:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4342:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4343: 
 4344:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4345:                                             } else {
 4346:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4347:                                             }
 4348:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4349:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4350:                                             }
 4351:                                         }
 4352:                                     }
 4353:                                 }
 4354:                             }
 4355:                         } else {
 4356:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4357:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4358:                                     $domconfig{'login'}{$key}{$img};
 4359:                             }
 4360:                         }
 4361:                     } else {
 4362:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4363:                     }
 4364:                 }
 4365:             } else {
 4366:                 $legacy{'login'} = 1;
 4367:             }
 4368:         } else {
 4369:             $legacy{'login'} = 1;
 4370:         }
 4371:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4372:             if (keys(%{$domconfig{'rolecolors'}})) {
 4373:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4374:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4375:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4376:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4377:                         }
 4378:                     }
 4379:                 }
 4380:             } else {
 4381:                 $legacy{'rolecolors'} = 1;
 4382:             }
 4383:         } else {
 4384:             $legacy{'rolecolors'} = 1;
 4385:         }
 4386:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4387:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4388:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4389:             }
 4390:         }
 4391:         if (keys(%legacy) > 0) {
 4392:             my %legacyhash = &get_legacy_domconf($udom);
 4393:             foreach my $item (keys(%legacyhash)) {
 4394:                 if ($item =~ /^\Q$udom\E\.login/) {
 4395:                     if ($legacy{'login'}) { 
 4396:                         $designhash{$item} = $legacyhash{$item};
 4397:                     }
 4398:                 } else {
 4399:                     if ($legacy{'rolecolors'}) {
 4400:                         $designhash{$item} = $legacyhash{$item};
 4401:                     }
 4402:                 }
 4403:             }
 4404:         }
 4405:     } else {
 4406:         %designhash = &get_legacy_domconf($udom); 
 4407:     }
 4408:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4409: 				  $cachetime);
 4410:     return %designhash;
 4411: }
 4412: 
 4413: sub get_legacy_domconf {
 4414:     my ($udom) = @_;
 4415:     my %legacyhash;
 4416:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4417:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4418:     if (-e $designfile) {
 4419:         if ( open (my $fh,"<$designfile") ) {
 4420:             while (my $line = <$fh>) {
 4421:                 next if ($line =~ /^\#/);
 4422:                 chomp($line);
 4423:                 my ($key,$val)=(split(/\=/,$line));
 4424:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4425:             }
 4426:             close($fh);
 4427:         }
 4428:     }
 4429:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4430:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4431:     }
 4432:     return %legacyhash;
 4433: }
 4434: 
 4435: =pod
 4436: 
 4437: =item * &domainlogo()
 4438: 
 4439: Inputs: $domain (usually will be undef)
 4440: 
 4441: Returns: A link to a domain logo, if the domain logo exists.
 4442: If the domain logo does not exist, a description of the domain.
 4443: 
 4444: =cut
 4445: 
 4446: ###############################################
 4447: sub domainlogo {
 4448:     my $domain = &determinedomain(shift);
 4449:     my %designhash = &get_domainconf($domain);    
 4450:     # See if there is a logo
 4451:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4452:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4453:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4454: 	    if ($imgsrc =~ m{^/res/}) {
 4455: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4456: 		&Apache::lonnet::repcopy($local_name);
 4457: 	    }
 4458: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4459:         } 
 4460:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4461:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4462:         return &Apache::lonnet::domain($domain,'description');
 4463:     } else {
 4464:         return '';
 4465:     }
 4466: }
 4467: ##############################################
 4468: 
 4469: =pod
 4470: 
 4471: =item * &designparm()
 4472: 
 4473: Inputs: $which parameter; $domain (usually will be undef)
 4474: 
 4475: Returns: value of designparamter $which
 4476: 
 4477: =cut
 4478: 
 4479: 
 4480: ##############################################
 4481: sub designparm {
 4482:     my ($which,$domain)=@_;
 4483:     if (exists($env{'environment.color.'.$which})) {
 4484:         return $env{'environment.color.'.$which};
 4485:     }
 4486:     $domain=&determinedomain($domain);
 4487:     my %domdesign;
 4488:     unless ($domain eq 'public') {
 4489:         %domdesign = &get_domainconf($domain);
 4490:     }
 4491:     my $output;
 4492:     if ($domdesign{$domain.'.'.$which} ne '') {
 4493:         $output = $domdesign{$domain.'.'.$which};
 4494:     } else {
 4495:         $output = $defaultdesign{$which};
 4496:     }
 4497:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4498:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4499:         if ($output =~ m{^/(adm|res)/}) {
 4500:             if ($output =~ m{^/res/}) {
 4501:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4502:                 &Apache::lonnet::repcopy($local_name);
 4503:             }
 4504:             $output = &lonhttpdurl($output);
 4505:         }
 4506:     }
 4507:     return $output;
 4508: }
 4509: 
 4510: ##############################################
 4511: =pod
 4512: 
 4513: =item * &authorspace()
 4514: 
 4515: Inputs: ./.
 4516: 
 4517: Returns: Path to the Construction Space of the current user's
 4518:          accessed author space
 4519:          The author space will be that of the current user
 4520:          when accessing the own author space
 4521:          and that of the co-author/assistent co-author
 4522:          when accessing the co-author's/assistent co-author's
 4523:          space
 4524: 
 4525: =cut
 4526: 
 4527: sub authorspace {
 4528:     my $caname = '';
 4529:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4530:         (undef,$caname) =
 4531:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4532:     } else {
 4533:         $caname = $env{'user.name'};
 4534:     }
 4535:     return '/priv/'.$caname.'/';
 4536: }
 4537: 
 4538: ##############################################
 4539: =pod
 4540: 
 4541: =item * &head_subbox()
 4542: 
 4543: Inputs: $content (contains HTML code with page functions, etc.)
 4544: 
 4545: Returns: HTML div with $content
 4546:          To be included in page header
 4547: 
 4548: =cut
 4549: 
 4550: sub head_subbox {
 4551:     my ($content)=@_;
 4552:     my $output =
 4553:         '<div class="LC_head_subbox">'
 4554:        .$content
 4555:        .'</div>'
 4556: }
 4557: 
 4558: ##############################################
 4559: =pod
 4560: 
 4561: =item * &CSTR_pageheader()
 4562: 
 4563: Input: (optional) filename from which breadcrumb trail is built.
 4564:        In most cases no input is needed, as $env{'request.filename'}
 4565:        is appropriate for use in building the breadcrumb trail.
 4566: 
 4567: Returns: HTML div with CSTR path and recent box
 4568:          To be included on Construction Space pages
 4569: 
 4570: =cut
 4571: 
 4572: sub CSTR_pageheader {
 4573:     my ($trailfile) = @_;
 4574:     if ($trailfile eq '') {
 4575:         $trailfile = $env{'request.filename'};
 4576:     }
 4577: 
 4578: # this is for resources; directories have customtitle, and crumbs
 4579: # and select recent are created in lonpubdir.pm  
 4580: 
 4581:     my ($uname,$thisdisfn)=
 4582:         ($trailfile =~ m|^/home/([^/]+)/public_html/(.*)|);
 4583:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4584:     $formaction=~s/\/+/\//g;
 4585: 
 4586:     my $parentpath = '';
 4587:     my $lastitem = '';
 4588:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4589:         $parentpath = $1;
 4590:         $lastitem = $2;
 4591:     } else {
 4592:         $lastitem = $thisdisfn;
 4593:     }
 4594: 
 4595:     my $output =
 4596:          '<div>'
 4597:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4598:         .'<b>'.&mt('Construction Space:').'</b> '
 4599:         .'<form name="dirs" method="post" action="'.$formaction
 4600:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4601:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
 4602: 
 4603:     if ($lastitem) {
 4604:         $output .=
 4605:              '<span class="LC_filename">'
 4606:             .$lastitem
 4607:             .'</span>';
 4608:     }
 4609:     $output .=
 4610:          '<br />'
 4611:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4612:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4613:         .'</form>'
 4614:         .&Apache::lonmenu::constspaceform()
 4615:         .'</div>';
 4616: 
 4617:     return $output;
 4618: }
 4619: 
 4620: ###############################################
 4621: ###############################################
 4622: 
 4623: =pod
 4624: 
 4625: =back
 4626: 
 4627: =head1 HTML Helpers
 4628: 
 4629: =over 4
 4630: 
 4631: =item * &bodytag()
 4632: 
 4633: Returns a uniform header for LON-CAPA web pages.
 4634: 
 4635: Inputs: 
 4636: 
 4637: =over 4
 4638: 
 4639: =item * $title, A title to be displayed on the page.
 4640: 
 4641: =item * $function, the current role (can be undef).
 4642: 
 4643: =item * $addentries, extra parameters for the <body> tag.
 4644: 
 4645: =item * $bodyonly, if defined, only return the <body> tag.
 4646: 
 4647: =item * $domain, if defined, force a given domain.
 4648: 
 4649: =item * $forcereg, if page should register as content page (relevant for 
 4650:             text interface only)
 4651: 
 4652: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4653:                      navigational links
 4654: 
 4655: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4656: 
 4657: =item * $no_inline_link, if true and in remote mode, don't show the 
 4658:          'Switch To Inline Menu' link
 4659: 
 4660: =item * $args, optional argument valid values are
 4661:             no_auto_mt_title -> prevents &mt()ing the title arg
 4662:             inherit_jsmath -> when creating popup window in a page,
 4663:                               should it have jsmath forced on by the
 4664:                               current page
 4665: 
 4666: =back
 4667: 
 4668: Returns: A uniform header for LON-CAPA web pages.  
 4669: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4670: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4671: other decorations will be returned.
 4672: 
 4673: =cut
 4674: 
 4675: sub bodytag {
 4676:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4677:         $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
 4678: 
 4679:     my $public;
 4680:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4681:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4682:         $public = 1;
 4683:     }
 4684:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4685: 
 4686:     $function = &get_users_function() if (!$function);
 4687:     my $img =    &designparm($function.'.img',$domain);
 4688:     my $font =   &designparm($function.'.font',$domain);
 4689:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4690: 
 4691:     my %design = ( 'style'   => 'margin-top: 0',
 4692: 		   'bgcolor' => $pgbg,
 4693: 		   'text'    => $font,
 4694:                    'alink'   => &designparm($function.'.alink',$domain),
 4695: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4696: 		   'link'    => &designparm($function.'.link',$domain),);
 4697:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4698: 
 4699:  # role and realm
 4700:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4701:     if ($role  eq 'ca') {
 4702:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4703:         $realm = &plainname($rname,$rdom);
 4704:     } 
 4705: # realm
 4706:     if ($env{'request.course.id'}) {
 4707:         if ($env{'request.role'} !~ /^cr/) {
 4708:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4709:         }
 4710:         if ($env{'request.course.sec'}) {
 4711:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4712:         }   
 4713: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4714:     } else {
 4715:         $role = &Apache::lonnet::plaintext($role);
 4716:     }
 4717: 
 4718:     if (!$realm) { $realm='&nbsp;'; }
 4719: # Set messages
 4720:     my $messages=&domainlogo($domain);
 4721: 
 4722:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4723: 
 4724: # construct main body tag
 4725:     my $bodytag = "<body $extra_body_attr>".
 4726: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4727: 
 4728:     if ($bodyonly) {
 4729:         return $bodytag;
 4730:     } 
 4731: 
 4732:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4733:     if ($public) {
 4734: 	undef($role);
 4735:     } else {
 4736: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4737:     }
 4738: 
 4739:     my $titleinfo = '<h1>'.$title.'</h1>';
 4740:     #
 4741:     # Extra info if you are the DC
 4742:     my $dc_info = '';
 4743:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4744:                         $env{'course.'.$env{'request.course.id'}.
 4745:                                  '.domain'}.'/'})) {
 4746:         my $cid = $env{'request.course.id'};
 4747:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4748:         $dc_info =~ s/\s+$//;
 4749:     }
 4750: 
 4751:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4752:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4753: 
 4754:     if ($env{'environment.remote'} ne 'on') {
 4755:         # No Remote
 4756:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4757:             return $bodytag;
 4758:         }
 4759: 
 4760:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4761: 
 4762:         #    if ($env{'request.state'} eq 'construct') {
 4763:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4764:         #    }
 4765: 
 4766: 
 4767: 
 4768:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4769:              if ($dc_info) {
 4770:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4771:              }
 4772:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4773:                 <em>$realm</em> $dc_info</div>|;
 4774:             return $bodytag;
 4775:         }
 4776:         if (($env{'request.noversionuri'} =~ m{^/adm/navmaps}) &&
 4777:              ($env{'environment.remotenavmap'} eq 'on')) {
 4778:             return $bodytag;
 4779:         }
 4780: 
 4781:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4782:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4783:         }
 4784: 
 4785:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4786:             Apache::lonmenu::utilityfunctions(), 'start');
 4787: 
 4788:         $bodytag .= Apache::lonmenu::primary_menu();
 4789: 
 4790:         if ($dc_info) {
 4791:             $dc_info = &dc_courseid_toggle($dc_info);
 4792:         }
 4793:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4794: 
 4795:         #don't show menus for public users
 4796:         if (!$public){
 4797:             $bodytag .= Apache::lonmenu::secondary_menu();
 4798:             $bodytag .= Apache::lonmenu::serverform();
 4799:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4800:             if ($env{'request.state'} eq 'construct') {
 4801:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,'',
 4802:                                 $args->{'bread_crumbs'});
 4803:             } elsif ($forcereg) { 
 4804:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4805:             }
 4806:         }else{
 4807:             # this is to seperate menu from content when there's no secondary
 4808:             # menu. Especially needed for public accessible ressources.
 4809:             $bodytag .= '<hr style="clear:both" />';
 4810:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4811:         }
 4812: 
 4813:         return $bodytag;
 4814:     }
 4815: 
 4816: #
 4817: # Top frame rendering, Remote is up
 4818: #
 4819: 
 4820:     my $imgsrc = $img;
 4821:     if ($img =~ /^\/adm/) {
 4822:         $imgsrc = &lonhttpdurl($img);
 4823:     }
 4824:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4825: 
 4826:     # Explicit link to get inline menu
 4827:     my $menu= ($no_inline_link?''
 4828: 	       :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 4829: 
 4830:     if ($dc_info) {
 4831:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 4832:     }
 4833: 
 4834:     unless ($env{'form.inhibitmenu'}) {
 4835:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 4836:                        <ol class="LC_primary_menu LC_right">
 4837:                        <li>$menu</li>
 4838:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 4839:     }
 4840: 
 4841:     return(<<ENDBODY);
 4842: $bodytag
 4843: <table id="LC_title_bar" class="LC_with_remote">
 4844: <tr><td>$upperleft</td>
 4845:     <td>$messages&nbsp;</td>
 4846: </tr>
 4847: <tr><td>$titleinfo $dc_info $menu</td>
 4848: </tr>
 4849: </table>
 4850: ENDBODY
 4851: }
 4852: 
 4853: sub dc_courseid_toggle {
 4854:     my ($dc_info) = @_;
 4855:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 4856:            '<a href="javascript:showCourseID();">'.
 4857:            &mt('(More ...)').'</a></span>'.
 4858:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4859: }
 4860: 
 4861: sub make_attr_string {
 4862:     my ($register,$attr_ref) = @_;
 4863: 
 4864:     if ($attr_ref && !ref($attr_ref)) {
 4865: 	die("addentries Must be a hash ref ".
 4866: 	    join(':',caller(1))." ".
 4867: 	    join(':',caller(0))." ");
 4868:     }
 4869: 
 4870:     if ($register) {
 4871: 	my ($on_load,$on_unload);
 4872: 	foreach my $key (keys(%{$attr_ref})) {
 4873: 	    if      (lc($key) eq 'onload') {
 4874: 		$on_load.=$attr_ref->{$key}.';';
 4875: 		delete($attr_ref->{$key});
 4876: 
 4877: 	    } elsif (lc($key) eq 'onunload') {
 4878: 		$on_unload.=$attr_ref->{$key}.';';
 4879: 		delete($attr_ref->{$key});
 4880: 	    }
 4881: 	}
 4882: 	$attr_ref->{'onload'}  =
 4883: 	    &Apache::lonmenu::loadevents().  $on_load;
 4884: 	$attr_ref->{'onunload'}=
 4885: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4886:     }
 4887: 
 4888: # Accessibility font enhance
 4889:     if ($env{'browser.fontenhance'} eq 'on') {
 4890: 	my $style;
 4891: 	foreach my $key (keys(%{$attr_ref})) {
 4892: 	    if (lc($key) eq 'style') {
 4893: 		$style.=$attr_ref->{$key}.';';
 4894: 		delete($attr_ref->{$key});
 4895: 	    }
 4896: 	}
 4897: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4898:     }
 4899: 
 4900:     my $attr_string;
 4901:     foreach my $attr (keys(%$attr_ref)) {
 4902: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4903:     }
 4904:     return $attr_string;
 4905: }
 4906: 
 4907: 
 4908: ###############################################
 4909: ###############################################
 4910: 
 4911: =pod
 4912: 
 4913: =item * &endbodytag()
 4914: 
 4915: Returns a uniform footer for LON-CAPA web pages.
 4916: 
 4917: Inputs: 1 - optional reference to an args hash
 4918: If in the hash, key for noredirectlink has a value which evaluates to true,
 4919: a 'Continue' link is not displayed if the page contains an
 4920: internal redirect in the <head></head> section,
 4921: i.e., $env{'internal.head.redirect'} exists   
 4922: 
 4923: =cut
 4924: 
 4925: sub endbodytag {
 4926:     my ($args) = @_;
 4927:     my $endbodytag='</body>';
 4928:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4929:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4930:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4931: 	    $endbodytag=
 4932: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4933: 	        &mt('Continue').'</a>'.
 4934: 	        $endbodytag;
 4935:         }
 4936:     }
 4937:     return $endbodytag;
 4938: }
 4939: 
 4940: =pod
 4941: 
 4942: =item * &standard_css()
 4943: 
 4944: Returns a style sheet
 4945: 
 4946: Inputs: (all optional)
 4947:             domain         -> force to color decorate a page for a specific
 4948:                                domain
 4949:             function       -> force usage of a specific rolish color scheme
 4950:             bgcolor        -> override the default page bgcolor
 4951: 
 4952: =cut
 4953: 
 4954: sub standard_css {
 4955:     my ($function,$domain,$bgcolor) = @_;
 4956:     $function  = &get_users_function() if (!$function);
 4957:     my $img    = &designparm($function.'.img',   $domain);
 4958:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4959:     my $font   = &designparm($function.'.font',  $domain);
 4960:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4961: #second colour for later usage
 4962:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4963:     my $pgbg_or_bgcolor =
 4964: 	         $bgcolor ||
 4965: 	         &designparm($function.'.pgbg',  $domain);
 4966:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4967:     my $alink  = &designparm($function.'.alink', $domain);
 4968:     my $vlink  = &designparm($function.'.vlink', $domain);
 4969:     my $link   = &designparm($function.'.link',  $domain);
 4970: 
 4971:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4972:     my $mono                 = 'monospace';
 4973:     my $data_table_head      = $sidebg;
 4974:     my $data_table_light     = '#FAFAFA';
 4975:     my $data_table_dark      = '#F0F0F0';
 4976:     my $data_table_darker    = '#CCCCCC';
 4977:     my $data_table_highlight = '#FFFF00';
 4978:     my $mail_new             = '#FFBB77';
 4979:     my $mail_new_hover       = '#DD9955';
 4980:     my $mail_read            = '#BBBB77';
 4981:     my $mail_read_hover      = '#999944';
 4982:     my $mail_replied         = '#AAAA88';
 4983:     my $mail_replied_hover   = '#888855';
 4984:     my $mail_other           = '#99BBBB';
 4985:     my $mail_other_hover     = '#669999';
 4986:     my $table_header         = '#DDDDDD';
 4987:     my $feedback_link_bg     = '#BBBBBB';
 4988:     my $lg_border_color      = '#C8C8C8';
 4989:     my $button_hover         = '#BF2317';
 4990: 
 4991:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4992:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4993:                                              : '0 3px 0 4px';
 4994: 
 4995:     return <<END;
 4996: 
 4997: /* needed for iframe to allow 100% height in FF */
 4998: body, html { 
 4999:     margin: 0;
 5000:     padding: 0 0.5%;
 5001:     height: 99%; /* to avoid scrollbars */
 5002: }
 5003: 
 5004: body {
 5005:   font-family: $sans;
 5006:   line-height:130%;
 5007:   font-size:0.83em;
 5008:   color:$font;
 5009: }
 5010: 
 5011: a:focus,
 5012: a:focus img {
 5013:   color: red;
 5014:   background: yellow;
 5015: }
 5016: 
 5017: form, .inline {
 5018:   display: inline;
 5019: }
 5020: 
 5021: .LC_right {
 5022:   text-align:right;
 5023: }
 5024: 
 5025: .LC_middle {
 5026:   vertical-align:middle;
 5027: }
 5028: 
 5029: .LC_400Box {
 5030:   width:400px;
 5031: }
 5032: 
 5033: .LC_iframecontainer {
 5034:     width: 98%;
 5035:     margin: 0;
 5036:     position: fixed;
 5037:     top: 8.5em;
 5038:     bottom: 0;
 5039: }
 5040: 
 5041: .LC_iframecontainer iframe{
 5042:     border: none;
 5043:     width: 100%;
 5044:     height: 100%;
 5045: }
 5046: 
 5047: .LC_filename {
 5048:   font-family: $mono;
 5049:   white-space:pre;
 5050:   font-size: 120%;
 5051: }
 5052: 
 5053: .LC_fileicon {
 5054:   border: none;
 5055:   height: 1.3em;
 5056:   vertical-align: text-bottom;
 5057:   margin-right: 0.3em;
 5058:   text-decoration:none;
 5059: }
 5060: 
 5061: .LC_error {
 5062:   color: red;
 5063:   font-size: larger;
 5064: }
 5065: 
 5066: .LC_warning,
 5067: .LC_diff_removed {
 5068:   color: red;
 5069: }
 5070: 
 5071: .LC_info,
 5072: .LC_success,
 5073: .LC_diff_added {
 5074:   color: green;
 5075: }
 5076: 
 5077: div.LC_confirm_box {
 5078:   background-color: #FAFAFA;
 5079:   border: 1px solid $lg_border_color;
 5080:   margin-right: 0;
 5081:   padding: 5px;
 5082: }
 5083: 
 5084: div.LC_confirm_box .LC_error img,
 5085: div.LC_confirm_box .LC_success img {
 5086:   vertical-align: middle;
 5087: }
 5088: 
 5089: .LC_icon {
 5090:   border: none;
 5091:   vertical-align: middle;
 5092: }
 5093: 
 5094: .LC_docs_spacer {
 5095:   width: 25px;
 5096:   height: 1px;
 5097:   border: none;
 5098: }
 5099: 
 5100: .LC_internal_info {
 5101:   color: #999999;
 5102: }
 5103: 
 5104: .LC_discussion {
 5105:   background: $tabbg;
 5106:   border: 1px solid black;
 5107:   margin: 2px;
 5108: }
 5109: 
 5110: .LC_disc_action_links_bar {
 5111:   background: $tabbg;
 5112:   border: none;
 5113:   margin: 4px;
 5114: }
 5115: 
 5116: .LC_disc_action_left {
 5117:   text-align: left;
 5118: }
 5119: 
 5120: .LC_disc_action_right {
 5121:   text-align: right;
 5122: }
 5123: 
 5124: .LC_disc_new_item {
 5125:   background: white;
 5126:   border: 2px solid red;
 5127:   margin: 2px;
 5128: }
 5129: 
 5130: .LC_disc_old_item {
 5131:   background: white;
 5132:   border: 1px solid black;
 5133:   margin: 2px;
 5134: }
 5135: 
 5136: table.LC_pastsubmission {
 5137:   border: 1px solid black;
 5138:   margin: 2px;
 5139: }
 5140: 
 5141: table#LC_menubuttons {
 5142:   width: 100%;
 5143:   background: $pgbg;
 5144:   border: 2px;
 5145:   border-collapse: separate;
 5146:   padding: 0;
 5147: }
 5148: 
 5149: table#LC_title_bar a {
 5150:   color: $fontmenu;
 5151: }
 5152: 
 5153: table#LC_title_bar {
 5154:   clear: both;
 5155:   display: none;
 5156: }
 5157: 
 5158: table#LC_title_bar,
 5159: table.LC_breadcrumbs, /* obsolete? */
 5160: table#LC_title_bar.LC_with_remote {
 5161:   width: 100%;
 5162:   border-color: $pgbg;
 5163:   border-style: solid;
 5164:   border-width: $border;
 5165:   background: $pgbg;
 5166:   color: $fontmenu;
 5167:   border-collapse: collapse;
 5168:   padding: 0;
 5169:   margin: 0;
 5170: }
 5171: 
 5172: ul.LC_breadcrumb_tools_outerlist {
 5173:     margin: 0;
 5174:     padding: 0;
 5175:     position: relative;
 5176:     list-style: none;
 5177: }
 5178: ul.LC_breadcrumb_tools_outerlist li {
 5179:     display: inline;
 5180: }
 5181: 
 5182: .LC_breadcrumb_tools_navigation {
 5183:     padding: 0;
 5184:     margin: 0;
 5185:     float: left;
 5186: }
 5187: .LC_breadcrumb_tools_tools {
 5188:     padding: 0;
 5189:     margin: 0;
 5190:     float: right;
 5191: }
 5192: 
 5193: table#LC_title_bar td {
 5194:   background: $tabbg;
 5195: }
 5196: 
 5197: table#LC_menubuttons img {
 5198:   border: none;
 5199: }
 5200: 
 5201: .LC_breadcrumbs_component {
 5202:   float: right;
 5203:   margin: 0 1em;
 5204: }
 5205: .LC_breadcrumbs_component img {
 5206:   vertical-align: middle;
 5207: }
 5208: 
 5209: td.LC_table_cell_checkbox {
 5210:   text-align: center;
 5211: }
 5212: 
 5213: .LC_fontsize_small {
 5214:   font-size: 70%;
 5215: }
 5216: 
 5217: #LC_breadcrumbs {
 5218:   clear:both;
 5219:   background: $sidebg;
 5220:   border-bottom: 1px solid $lg_border_color;
 5221:   line-height: 2.5em;
 5222:   overflow: hidden;
 5223:   margin: 0;
 5224:   padding: 0;
 5225:   text-align: left;
 5226: }
 5227: 
 5228: /* Preliminary fix to hide breadcrumbs inside remote control window */
 5229: #LC_remote #LC_breadcrumbs {
 5230:   display:none;
 5231: }
 5232: 
 5233: .LC_head_subbox {
 5234:   clear:both;
 5235:   background: #F8F8F8; /* $sidebg; */
 5236:   border: 1px solid $sidebg;
 5237:   margin: 0 0 10px 0;      
 5238:   padding: 3px;
 5239:   text-align: left;
 5240: }
 5241: 
 5242: .LC_fontsize_medium {
 5243:   font-size: 85%;
 5244: }
 5245: 
 5246: .LC_fontsize_large {
 5247:   font-size: 120%;
 5248: }
 5249: 
 5250: .LC_menubuttons_inline_text {
 5251:   color: $font;
 5252:   font-size: 90%;
 5253:   padding-left:3px;
 5254: }
 5255: 
 5256: .LC_menubuttons_inline_text img{
 5257:   vertical-align: middle;
 5258: }
 5259: 
 5260: li.LC_menubuttons_inline_text img,a {
 5261:   cursor:pointer;
 5262:   text-decoration: none;
 5263: }
 5264: 
 5265: .LC_menubuttons_link {
 5266:   text-decoration: none;
 5267: }
 5268: 
 5269: .LC_menubuttons_category {
 5270:   color: $font;
 5271:   background: $pgbg;
 5272:   font-size: larger;
 5273:   font-weight: bold;
 5274: }
 5275: 
 5276: td.LC_menubuttons_text {
 5277:   color: $font;
 5278: }
 5279: 
 5280: .LC_current_location {
 5281:   background: $tabbg;
 5282: }
 5283: 
 5284: table.LC_data_table {
 5285:   border: 1px solid #000000;
 5286:   border-collapse: separate;
 5287:   border-spacing: 1px;
 5288:   background: $pgbg;
 5289: }
 5290: 
 5291: .LC_data_table_dense {
 5292:   font-size: small;
 5293: }
 5294: 
 5295: table.LC_nested_outer {
 5296:   border: 1px solid #000000;
 5297:   border-collapse: collapse;
 5298:   border-spacing: 0;
 5299:   width: 100%;
 5300: }
 5301: 
 5302: table.LC_innerpickbox,
 5303: table.LC_nested {
 5304:   border: none;
 5305:   border-collapse: collapse;
 5306:   border-spacing: 0;
 5307:   width: 100%;
 5308: }
 5309: 
 5310: .ui-accordion,
 5311: .ui-accordion table.LC_data_table,
 5312: .ui-accordion table.LC_nested_outer{
 5313:   border: 0px;
 5314:   border-spacing: 0px;
 5315:   margin: 3px;
 5316: }
 5317: 
 5318: table.LC_data_table tr th,
 5319: table.LC_calendar tr th,
 5320: table.LC_prior_tries tr th,
 5321: table.LC_innerpickbox tr th {
 5322:   font-weight: bold;
 5323:   background-color: $data_table_head;
 5324:   color:$fontmenu;
 5325:   font-size:90%;
 5326: }
 5327: 
 5328: table.LC_innerpickbox tr th,
 5329: table.LC_innerpickbox tr td {
 5330:   vertical-align: top;
 5331: }
 5332: 
 5333: table.LC_data_table tr.LC_info_row > td {
 5334:   background-color: #CCCCCC;
 5335:   font-weight: bold;
 5336:   text-align: left;
 5337: }
 5338: 
 5339: table.LC_data_table tr.LC_odd_row > td {
 5340:   background-color: $data_table_light;
 5341:   padding: 2px;
 5342:   vertical-align: top;
 5343: }
 5344: 
 5345: table.LC_pick_box tr > td.LC_odd_row {
 5346:   background-color: $data_table_light;
 5347:   vertical-align: top;
 5348: }
 5349: 
 5350: table.LC_data_table tr.LC_even_row > td {
 5351:   background-color: $data_table_dark;
 5352:   padding: 2px;
 5353:   vertical-align: top;
 5354: }
 5355: 
 5356: table.LC_pick_box tr > td.LC_even_row {
 5357:   background-color: $data_table_dark;
 5358:   vertical-align: top;
 5359: }
 5360: 
 5361: table.LC_data_table tr.LC_data_table_highlight td {
 5362:   background-color: $data_table_darker;
 5363: }
 5364: 
 5365: table.LC_data_table tr td.LC_leftcol_header {
 5366:   background-color: $data_table_head;
 5367:   font-weight: bold;
 5368: }
 5369: 
 5370: table.LC_data_table tr.LC_empty_row td,
 5371: table.LC_nested tr.LC_empty_row td {
 5372:   font-weight: bold;
 5373:   font-style: italic;
 5374:   text-align: center;
 5375:   padding: 8px;
 5376: }
 5377: 
 5378: table.LC_data_table tr.LC_empty_row td {
 5379:   background-color: $sidebg;
 5380: }
 5381: 
 5382: table.LC_nested tr.LC_empty_row td {
 5383:   background-color: #FFFFFF;
 5384: }
 5385: 
 5386: table.LC_caption {
 5387: }
 5388: 
 5389: table.LC_nested tr.LC_empty_row td {
 5390:   padding: 4ex
 5391: }
 5392: 
 5393: table.LC_nested_outer tr th {
 5394:   font-weight: bold;
 5395:   color:$fontmenu;
 5396:   background-color: $data_table_head;
 5397:   font-size: small;
 5398:   border-bottom: 1px solid #000000;
 5399: }
 5400: 
 5401: table.LC_nested_outer tr td.LC_subheader {
 5402:   background-color: $data_table_head;
 5403:   font-weight: bold;
 5404:   font-size: small;
 5405:   border-bottom: 1px solid #000000;
 5406:   text-align: right;
 5407: }
 5408: 
 5409: table.LC_nested tr.LC_info_row td {
 5410:   background-color: #CCCCCC;
 5411:   font-weight: bold;
 5412:   font-size: small;
 5413:   text-align: center;
 5414: }
 5415: 
 5416: table.LC_nested tr.LC_info_row td.LC_left_item,
 5417: table.LC_nested_outer tr th.LC_left_item {
 5418:   text-align: left;
 5419: }
 5420: 
 5421: table.LC_nested td {
 5422:   background-color: #FFFFFF;
 5423:   font-size: small;
 5424: }
 5425: 
 5426: table.LC_nested_outer tr th.LC_right_item,
 5427: table.LC_nested tr.LC_info_row td.LC_right_item,
 5428: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5429: table.LC_nested tr td.LC_right_item {
 5430:   text-align: right;
 5431: }
 5432: 
 5433: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_left_item,
 5434: .ui-accordion table.LC_nested tr.LC_even_row td.LC_left_item {
 5435:   text-align: right;
 5436:   width: 40%;
 5437:   padding-right:10px;
 5438:   vertical-align: top;
 5439:   padding: 5px;
 5440: }
 5441: 
 5442: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_right_item,
 5443: .ui-accordion table.LC_nested tr.LC_even_row td.LC_right_item {
 5444:   text-align: left;
 5445:   width: 60%;
 5446:   padding: 2px 4px;
 5447: }
 5448: 
 5449: table.LC_nested tr.LC_odd_row td {
 5450:   background-color: #EEEEEE;
 5451: }
 5452: 
 5453: table.LC_createuser {
 5454: }
 5455: 
 5456: table.LC_createuser tr.LC_section_row td {
 5457:   font-size: small;
 5458: }
 5459: 
 5460: table.LC_createuser tr.LC_info_row td  {
 5461:   background-color: #CCCCCC;
 5462:   font-weight: bold;
 5463:   text-align: center;
 5464: }
 5465: 
 5466: table.LC_calendar {
 5467:   border: 1px solid #000000;
 5468:   border-collapse: collapse;
 5469:   width: 98%;
 5470: }
 5471: 
 5472: table.LC_calendar_pickdate {
 5473:   font-size: xx-small;
 5474: }
 5475: 
 5476: table.LC_calendar tr td {
 5477:   border: 1px solid #000000;
 5478:   vertical-align: top;
 5479:   width: 14%;
 5480: }
 5481: 
 5482: table.LC_calendar tr td.LC_calendar_day_empty {
 5483:   background-color: $data_table_dark;
 5484: }
 5485: 
 5486: table.LC_calendar tr td.LC_calendar_day_current {
 5487:   background-color: $data_table_highlight;
 5488: }
 5489: 
 5490: table.LC_data_table tr td.LC_mail_new {
 5491:   background-color: $mail_new;
 5492: }
 5493: 
 5494: table.LC_data_table tr.LC_mail_new:hover {
 5495:   background-color: $mail_new_hover;
 5496: }
 5497: 
 5498: table.LC_data_table tr td.LC_mail_read {
 5499:   background-color: $mail_read;
 5500: }
 5501: 
 5502: /*
 5503: table.LC_data_table tr.LC_mail_read:hover {
 5504:   background-color: $mail_read_hover;
 5505: }
 5506: */
 5507: 
 5508: table.LC_data_table tr td.LC_mail_replied {
 5509:   background-color: $mail_replied;
 5510: }
 5511: 
 5512: /*
 5513: table.LC_data_table tr.LC_mail_replied:hover {
 5514:   background-color: $mail_replied_hover;
 5515: }
 5516: */
 5517: 
 5518: table.LC_data_table tr td.LC_mail_other {
 5519:   background-color: $mail_other;
 5520: }
 5521: 
 5522: /*
 5523: table.LC_data_table tr.LC_mail_other:hover {
 5524:   background-color: $mail_other_hover;
 5525: }
 5526: */
 5527: 
 5528: table.LC_data_table tr > td.LC_browser_file,
 5529: table.LC_data_table tr > td.LC_browser_file_published {
 5530:   background: #AAEE77;
 5531: }
 5532: 
 5533: table.LC_data_table tr > td.LC_browser_file_locked,
 5534: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5535:   background: #FFAA99;
 5536: }
 5537: 
 5538: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5539:   background: #888888;
 5540: }
 5541: 
 5542: table.LC_data_table tr > td.LC_browser_file_modified,
 5543: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5544:   background: #F8F866;
 5545: }
 5546: 
 5547: table.LC_data_table tr.LC_browser_folder > td {
 5548:   background: #E0E8FF;
 5549: }
 5550: 
 5551: table.LC_data_table tr > td.LC_roles_is {
 5552:   /* background: #77FF77; */
 5553: }
 5554: 
 5555: table.LC_data_table tr > td.LC_roles_future {
 5556:   border-right: 8px solid #FFFF77;
 5557: }
 5558: 
 5559: table.LC_data_table tr > td.LC_roles_will {
 5560:   border-right: 8px solid #FFAA77;
 5561: }
 5562: 
 5563: table.LC_data_table tr > td.LC_roles_expired {
 5564:   border-right: 8px solid #FF7777;
 5565: }
 5566: 
 5567: table.LC_data_table tr > td.LC_roles_will_not {
 5568:   border-right: 8px solid #AAFF77;
 5569: }
 5570: 
 5571: table.LC_data_table tr > td.LC_roles_selected {
 5572:   border-right: 8px solid #11CC55;
 5573: }
 5574: 
 5575: span.LC_current_location {
 5576:   font-size:larger;
 5577:   background: $pgbg;
 5578: }
 5579: 
 5580: span.LC_parm_menu_item {
 5581:   font-size: larger;
 5582: }
 5583: 
 5584: span.LC_parm_scope_all {
 5585:   color: red;
 5586: }
 5587: 
 5588: span.LC_parm_scope_folder {
 5589:   color: green;
 5590: }
 5591: 
 5592: span.LC_parm_scope_resource {
 5593:   color: orange;
 5594: }
 5595: 
 5596: span.LC_parm_part {
 5597:   color: blue;
 5598: }
 5599: 
 5600: span.LC_parm_folder,
 5601: span.LC_parm_symb {
 5602:   font-size: x-small;
 5603:   font-family: $mono;
 5604:   color: #AAAAAA;
 5605: }
 5606: 
 5607: ul.LC_parm_parmlist li {
 5608:   display: inline-block;
 5609:   padding: 0.3em 0.8em;
 5610:   vertical-align: top;
 5611:   width: 150px;
 5612:   border-top:1px solid $lg_border_color;
 5613: }
 5614: 
 5615: td.LC_parm_overview_level_menu,
 5616: td.LC_parm_overview_map_menu,
 5617: td.LC_parm_overview_parm_selectors,
 5618: td.LC_parm_overview_restrictions  {
 5619:   border: 1px solid black;
 5620:   border-collapse: collapse;
 5621: }
 5622: 
 5623: table.LC_parm_overview_restrictions td {
 5624:   border-width: 1px 4px 1px 4px;
 5625:   border-style: solid;
 5626:   border-color: $pgbg;
 5627:   text-align: center;
 5628: }
 5629: 
 5630: table.LC_parm_overview_restrictions th {
 5631:   background: $tabbg;
 5632:   border-width: 1px 4px 1px 4px;
 5633:   border-style: solid;
 5634:   border-color: $pgbg;
 5635: }
 5636: 
 5637: table#LC_helpmenu {
 5638:   border: none;
 5639:   height: 55px;
 5640:   border-spacing: 0;
 5641: }
 5642: 
 5643: table#LC_helpmenu fieldset legend {
 5644:   font-size: larger;
 5645: }
 5646: 
 5647: table#LC_helpmenu_links {
 5648:   width: 100%;
 5649:   border: 1px solid black;
 5650:   background: $pgbg;
 5651:   padding: 0;
 5652:   border-spacing: 1px;
 5653: }
 5654: 
 5655: table#LC_helpmenu_links tr td {
 5656:   padding: 1px;
 5657:   background: $tabbg;
 5658:   text-align: center;
 5659:   font-weight: bold;
 5660: }
 5661: 
 5662: table#LC_helpmenu_links a:link,
 5663: table#LC_helpmenu_links a:visited,
 5664: table#LC_helpmenu_links a:active {
 5665:   text-decoration: none;
 5666:   color: $font;
 5667: }
 5668: 
 5669: table#LC_helpmenu_links a:hover {
 5670:   text-decoration: underline;
 5671:   color: $vlink;
 5672: }
 5673: 
 5674: .LC_chrt_popup_exists {
 5675:   border: 1px solid #339933;
 5676:   margin: -1px;
 5677: }
 5678: 
 5679: .LC_chrt_popup_up {
 5680:   border: 1px solid yellow;
 5681:   margin: -1px;
 5682: }
 5683: 
 5684: .LC_chrt_popup {
 5685:   border: 1px solid #8888FF;
 5686:   background: #CCCCFF;
 5687: }
 5688: 
 5689: table.LC_pick_box {
 5690:   border-collapse: separate;
 5691:   background: white;
 5692:   border: 1px solid black;
 5693:   border-spacing: 1px;
 5694: }
 5695: 
 5696: table.LC_pick_box td.LC_pick_box_title {
 5697:   background: $sidebg;
 5698:   font-weight: bold;
 5699:   text-align: left;
 5700:   vertical-align: top;
 5701:   width: 184px;
 5702:   padding: 8px;
 5703: }
 5704: 
 5705: table.LC_pick_box td.LC_pick_box_value {
 5706:   text-align: left;
 5707:   padding: 8px;
 5708: }
 5709: 
 5710: table.LC_pick_box td.LC_pick_box_select {
 5711:   text-align: left;
 5712:   padding: 8px;
 5713: }
 5714: 
 5715: table.LC_pick_box td.LC_pick_box_separator {
 5716:   padding: 0;
 5717:   height: 1px;
 5718:   background: black;
 5719: }
 5720: 
 5721: table.LC_pick_box td.LC_pick_box_submit {
 5722:   text-align: right;
 5723: }
 5724: 
 5725: table.LC_pick_box td.LC_evenrow_value {
 5726:   text-align: left;
 5727:   padding: 8px;
 5728:   background-color: $data_table_light;
 5729: }
 5730: 
 5731: table.LC_pick_box td.LC_oddrow_value {
 5732:   text-align: left;
 5733:   padding: 8px;
 5734:   background-color: $data_table_light;
 5735: }
 5736: 
 5737: span.LC_helpform_receipt_cat {
 5738:   font-weight: bold;
 5739: }
 5740: 
 5741: table.LC_group_priv_box {
 5742:   background: white;
 5743:   border: 1px solid black;
 5744:   border-spacing: 1px;
 5745: }
 5746: 
 5747: table.LC_group_priv_box td.LC_pick_box_title {
 5748:   background: $tabbg;
 5749:   font-weight: bold;
 5750:   text-align: right;
 5751:   width: 184px;
 5752: }
 5753: 
 5754: table.LC_group_priv_box td.LC_groups_fixed {
 5755:   background: $data_table_light;
 5756:   text-align: center;
 5757: }
 5758: 
 5759: table.LC_group_priv_box td.LC_groups_optional {
 5760:   background: $data_table_dark;
 5761:   text-align: center;
 5762: }
 5763: 
 5764: table.LC_group_priv_box td.LC_groups_functionality {
 5765:   background: $data_table_darker;
 5766:   text-align: center;
 5767:   font-weight: bold;
 5768: }
 5769: 
 5770: table.LC_group_priv td {
 5771:   text-align: left;
 5772:   padding: 0;
 5773: }
 5774: 
 5775: table.LC_notify_front_page {
 5776:   background: white;
 5777:   border: 1px solid black;
 5778:   padding: 8px;
 5779: }
 5780: 
 5781: table.LC_notify_front_page td {
 5782:   padding: 8px;
 5783: }
 5784: 
 5785: .LC_navbuttons {
 5786:   margin: 2ex 0ex 2ex 0ex;
 5787: }
 5788: 
 5789: .LC_topic_bar {
 5790:   font-weight: bold;
 5791:   background: $tabbg;
 5792:   margin: 1em 0em 1em 2em;
 5793:   padding: 3px;
 5794:   font-size: 1.2em;
 5795: }
 5796: 
 5797: .LC_topic_bar span {
 5798:   left: 0.5em;
 5799:   position: absolute;
 5800:   vertical-align: middle;
 5801:   font-size: 1.2em;
 5802: }
 5803: 
 5804: table.LC_course_group_status {
 5805:   margin: 20px;
 5806: }
 5807: 
 5808: table.LC_status_selector td {
 5809:   vertical-align: top;
 5810:   text-align: center;
 5811:   padding: 4px;
 5812: }
 5813: 
 5814: div.LC_feedback_link {
 5815:   clear: both;
 5816:   background: $sidebg;
 5817:   width: 100%;
 5818:   padding-bottom: 10px;
 5819:   border: 1px $tabbg solid;
 5820:   height: 22px;
 5821:   line-height: 22px;
 5822:   padding-top: 5px;
 5823: }
 5824: 
 5825: div.LC_feedback_link img {
 5826:   height: 22px;
 5827:   vertical-align:middle;
 5828: }
 5829: 
 5830: div.LC_feedback_link a {
 5831:   text-decoration: none;
 5832: }
 5833: 
 5834: div.LC_comblock {
 5835:   display:inline;
 5836:   color:$font;
 5837:   font-size:90%;
 5838: }
 5839: 
 5840: div.LC_feedback_link div.LC_comblock {
 5841:   padding-left:5px;
 5842: }
 5843: 
 5844: div.LC_feedback_link div.LC_comblock a {
 5845:   color:$font;
 5846: }
 5847: 
 5848: span.LC_feedback_link {
 5849:   /* background: $feedback_link_bg; */
 5850:   font-size: larger;
 5851: }
 5852: 
 5853: span.LC_message_link {
 5854:   /* background: $feedback_link_bg; */
 5855:   font-size: larger;
 5856:   position: absolute;
 5857:   right: 1em;
 5858: }
 5859: 
 5860: table.LC_prior_tries {
 5861:   border: 1px solid #000000;
 5862:   border-collapse: separate;
 5863:   border-spacing: 1px;
 5864: }
 5865: 
 5866: table.LC_prior_tries td {
 5867:   padding: 2px;
 5868: }
 5869: 
 5870: .LC_answer_correct {
 5871:   background: lightgreen;
 5872:   color: darkgreen;
 5873:   padding: 6px;
 5874: }
 5875: 
 5876: .LC_answer_charged_try {
 5877:   background: #FFAAAA;
 5878:   color: darkred;
 5879:   padding: 6px;
 5880: }
 5881: 
 5882: .LC_answer_not_charged_try,
 5883: .LC_answer_no_grade,
 5884: .LC_answer_late {
 5885:   background: lightyellow;
 5886:   color: black;
 5887:   padding: 6px;
 5888: }
 5889: 
 5890: .LC_answer_previous {
 5891:   background: lightblue;
 5892:   color: darkblue;
 5893:   padding: 6px;
 5894: }
 5895: 
 5896: .LC_answer_no_message {
 5897:   background: #FFFFFF;
 5898:   color: black;
 5899:   padding: 6px;
 5900: }
 5901: 
 5902: .LC_answer_unknown {
 5903:   background: orange;
 5904:   color: black;
 5905:   padding: 6px;
 5906: }
 5907: 
 5908: span.LC_prior_numerical,
 5909: span.LC_prior_string,
 5910: span.LC_prior_custom,
 5911: span.LC_prior_reaction,
 5912: span.LC_prior_math {
 5913:   font-family: $mono;
 5914:   white-space: pre;
 5915: }
 5916: 
 5917: span.LC_prior_string {
 5918:   font-family: $mono;
 5919:   white-space: pre;
 5920: }
 5921: 
 5922: table.LC_prior_option {
 5923:   width: 100%;
 5924:   border-collapse: collapse;
 5925: }
 5926: 
 5927: table.LC_prior_rank,
 5928: table.LC_prior_match {
 5929:   border-collapse: collapse;
 5930: }
 5931: 
 5932: table.LC_prior_option tr td,
 5933: table.LC_prior_rank tr td,
 5934: table.LC_prior_match tr td {
 5935:   border: 1px solid #000000;
 5936: }
 5937: 
 5938: .LC_nobreak {
 5939:   white-space: nowrap;
 5940: }
 5941: 
 5942: span.LC_cusr_emph {
 5943:   font-style: italic;
 5944: }
 5945: 
 5946: span.LC_cusr_subheading {
 5947:   font-weight: normal;
 5948:   font-size: 85%;
 5949: }
 5950: 
 5951: div.LC_docs_entry_move {
 5952:   border: 1px solid #BBBBBB;
 5953:   background: #DDDDDD;
 5954:   width: 22px;
 5955:   padding: 1px;
 5956:   margin: 0;
 5957: }
 5958: 
 5959: table.LC_data_table tr > td.LC_docs_entry_commands,
 5960: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5961:   background: #DDDDDD;
 5962:   font-size: x-small;
 5963: }
 5964: 
 5965: .LC_docs_entry_parameter {
 5966:   white-space: nowrap;
 5967: }
 5968: 
 5969: .LC_docs_copy {
 5970:   color: #000099;
 5971: }
 5972: 
 5973: .LC_docs_cut {
 5974:   color: #550044;
 5975: }
 5976: 
 5977: .LC_docs_rename {
 5978:   color: #009900;
 5979: }
 5980: 
 5981: .LC_docs_remove {
 5982:   color: #990000;
 5983: }
 5984: 
 5985: .LC_docs_reinit_warn,
 5986: .LC_docs_ext_edit {
 5987:   font-size: x-small;
 5988: }
 5989: 
 5990: table.LC_docs_adddocs td,
 5991: table.LC_docs_adddocs th {
 5992:   border: 1px solid #BBBBBB;
 5993:   padding: 4px;
 5994:   background: #DDDDDD;
 5995: }
 5996: 
 5997: table.LC_sty_begin {
 5998:   background: #BBFFBB;
 5999: }
 6000: 
 6001: table.LC_sty_end {
 6002:   background: #FFBBBB;
 6003: }
 6004: 
 6005: table.LC_double_column {
 6006:   border-width: 0;
 6007:   border-collapse: collapse;
 6008:   width: 100%;
 6009:   padding: 2px;
 6010: }
 6011: 
 6012: table.LC_double_column tr td.LC_left_col {
 6013:   top: 2px;
 6014:   left: 2px;
 6015:   width: 47%;
 6016:   vertical-align: top;
 6017: }
 6018: 
 6019: table.LC_double_column tr td.LC_right_col {
 6020:   top: 2px;
 6021:   right: 2px;
 6022:   width: 47%;
 6023:   vertical-align: top;
 6024: }
 6025: 
 6026: div.LC_left_float {
 6027:   float: left;
 6028:   padding-right: 5%;
 6029:   padding-bottom: 4px;
 6030: }
 6031: 
 6032: div.LC_clear_float_header {
 6033:   padding-bottom: 2px;
 6034: }
 6035: 
 6036: div.LC_clear_float_footer {
 6037:   padding-top: 10px;
 6038:   clear: both;
 6039: }
 6040: 
 6041: div.LC_grade_show_user {
 6042: /*  border-left: 5px solid $sidebg; */
 6043:   border-top: 5px solid #000000;
 6044:   margin: 50px 0 0 0;
 6045:   padding: 15px 0 5px 10px;
 6046: }
 6047: 
 6048: div.LC_grade_show_user_odd_row {
 6049: /*  border-left: 5px solid #000000; */
 6050: }
 6051: 
 6052: div.LC_grade_show_user div.LC_Box {
 6053:   margin-right: 50px;
 6054: }
 6055: 
 6056: div.LC_grade_submissions,
 6057: div.LC_grade_message_center,
 6058: div.LC_grade_info_links {
 6059:   margin: 5px;
 6060:   width: 99%;
 6061:   background: #FFFFFF;
 6062: }
 6063: 
 6064: div.LC_grade_submissions_header,
 6065: div.LC_grade_message_center_header {
 6066:   font-weight: bold;
 6067:   font-size: large;
 6068: }
 6069: 
 6070: div.LC_grade_submissions_body,
 6071: div.LC_grade_message_center_body {
 6072:   border: 1px solid black;
 6073:   width: 99%;
 6074:   background: #FFFFFF;
 6075: }
 6076: 
 6077: table.LC_scantron_action {
 6078:   width: 100%;
 6079: }
 6080: 
 6081: table.LC_scantron_action tr th {
 6082:   font-weight:bold;
 6083:   font-style:normal;
 6084: }
 6085: 
 6086: .LC_edit_problem_header,
 6087: div.LC_edit_problem_footer {
 6088:   font-weight: normal;
 6089:   font-size:  medium;
 6090:   margin: 2px;
 6091: }
 6092: 
 6093: div.LC_edit_problem_header,
 6094: div.LC_edit_problem_header div,
 6095: div.LC_edit_problem_footer,
 6096: div.LC_edit_problem_footer div,
 6097: div.LC_edit_problem_editxml_header,
 6098: div.LC_edit_problem_editxml_header div {
 6099:   margin-top: 5px;
 6100: }
 6101: 
 6102: div.LC_edit_problem_header_title {
 6103:   font-weight: bold;
 6104:   font-size: larger;
 6105:   background: $tabbg;
 6106:   padding: 3px;
 6107: }
 6108: 
 6109: table.LC_edit_problem_header_title {
 6110:   width: 100%;
 6111:   background: $tabbg;
 6112: }
 6113: 
 6114: div.LC_edit_problem_discards {
 6115:   float: left;
 6116:   padding-bottom: 5px;
 6117: }
 6118: 
 6119: div.LC_edit_problem_saves {
 6120:   float: right;
 6121:   padding-bottom: 5px;
 6122: }
 6123: 
 6124: img.stift {
 6125:   border-width: 0;
 6126:   vertical-align: middle;
 6127: }
 6128: 
 6129: table td.LC_mainmenu_col_fieldset {
 6130:   vertical-align: top;
 6131: }
 6132: 
 6133: div.LC_createcourse {
 6134:   margin: 10px 10px 10px 10px;
 6135: }
 6136: 
 6137: .LC_dccid {
 6138:   margin: 0.2em 0 0 0;
 6139:   padding: 0;
 6140:   font-size: 90%;
 6141:   display:none;
 6142: }
 6143: 
 6144: a:hover,
 6145: ol.LC_primary_menu a:hover,
 6146: ol#LC_MenuBreadcrumbs a:hover,
 6147: ol#LC_PathBreadcrumbs a:hover,
 6148: ul#LC_secondary_menu a:hover,
 6149: .LC_FormSectionClearButton input:hover
 6150: ul.LC_TabContent   li:hover a {
 6151:   color:$button_hover;
 6152:   text-decoration:none;
 6153: }
 6154: 
 6155: h1 {
 6156:   padding: 0;
 6157:   line-height:130%;
 6158: }
 6159: 
 6160: h2,
 6161: h3,
 6162: h4,
 6163: h5,
 6164: h6 {
 6165:   margin: 5px 0 5px 0;
 6166:   padding: 0;
 6167:   line-height:130%;
 6168: }
 6169: 
 6170: .LC_hcell {
 6171:   padding:3px 15px 3px 15px;
 6172:   margin: 0;
 6173:   background-color:$tabbg;
 6174:   color:$fontmenu;
 6175:   border-bottom:solid 1px $lg_border_color;
 6176: }
 6177: 
 6178: .LC_Box > .LC_hcell {
 6179:   margin: 0 -10px 10px -10px;
 6180: }
 6181: 
 6182: .LC_noBorder {
 6183:   border: 0;
 6184: }
 6185: 
 6186: .LC_FormSectionClearButton input {
 6187:   background-color:transparent;
 6188:   border: none;
 6189:   cursor:pointer;
 6190:   text-decoration:underline;
 6191: }
 6192: 
 6193: .LC_help_open_topic {
 6194:   color: #FFFFFF;
 6195:   background-color: #EEEEFF;
 6196:   margin: 1px;
 6197:   padding: 4px;
 6198:   border: 1px solid #000033;
 6199:   white-space: nowrap;
 6200:   /* vertical-align: middle; */
 6201: }
 6202: 
 6203: dl,
 6204: ul,
 6205: div,
 6206: fieldset {
 6207:   margin: 10px 10px 10px 0;
 6208:   /* overflow: hidden; */
 6209: }
 6210: 
 6211: fieldset > legend {
 6212:   font-weight: bold;
 6213:   padding: 0 5px 0 5px;
 6214: }
 6215: 
 6216: #LC_nav_bar {
 6217:   float: left;
 6218:   background-color: $pgbg_or_bgcolor;
 6219:   margin: 0 0 2px 0;
 6220: }
 6221: 
 6222: #LC_realm {
 6223:   margin: 0.2em 0 0 0;
 6224:   padding: 0;
 6225:   font-weight: bold;
 6226:   text-align: center;
 6227:   background-color: $pgbg_or_bgcolor;
 6228: }
 6229: 
 6230: #LC_nav_bar em {
 6231:   font-weight: bold;
 6232:   font-style: normal;
 6233: }
 6234: 
 6235: /* Preliminary fix to hide nav_bar inside bookmarks window */
 6236: #LC_bookmarks #LC_nav_bar {
 6237:   display:none;
 6238: }
 6239: 
 6240: ol.LC_primary_menu {
 6241:   float: right;
 6242:   margin: 0;
 6243:   background-color: $pgbg_or_bgcolor;
 6244: }
 6245: 
 6246: ol.LC_primary_menu a.LC_new_message {
 6247:   font-weight:bold;
 6248:   color: darkred;
 6249: }
 6250: 
 6251: ol#LC_PathBreadcrumbs {
 6252:   margin: 0;
 6253: }
 6254: 
 6255: ol.LC_primary_menu li {
 6256:   display: inline;
 6257:   padding: 5px 5px 0 10px;
 6258:   vertical-align: top;
 6259: }
 6260: 
 6261: ol.LC_primary_menu li img {
 6262:   vertical-align: bottom;
 6263:   height: 1.1em;
 6264: }
 6265: 
 6266: ol.LC_primary_menu a {
 6267:   color: RGB(80, 80, 80);
 6268:   text-decoration: none;
 6269: }
 6270: 
 6271: ol.LC_docs_parameters {
 6272:   margin-left: 0;
 6273:   padding: 0;
 6274:   list-style: none;
 6275: }
 6276: 
 6277: ol.LC_docs_parameters li {
 6278:   margin: 0;
 6279:   padding-right: 20px;
 6280:   display: inline;
 6281: }
 6282: 
 6283: ol.LC_docs_parameters li:before {
 6284:   content: "\\002022 \\0020";
 6285: }
 6286: 
 6287: li.LC_docs_parameters_title {
 6288:   font-weight: bold;
 6289: }
 6290: 
 6291: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6292:   content: "";
 6293: }
 6294: 
 6295: ul#LC_secondary_menu {
 6296:   clear: both;
 6297:   color: $fontmenu;
 6298:   background: $tabbg;
 6299:   list-style: none;
 6300:   padding: 0;
 6301:   margin: 0;
 6302:   width: 100%;
 6303:   text-align: left;
 6304: }
 6305: 
 6306: ul#LC_secondary_menu li {
 6307:   font-weight: bold;
 6308:   line-height: 1.8em;
 6309:   padding: 0 0.8em;
 6310:   border-right: 1px solid black;
 6311:   display: inline;
 6312:   vertical-align: middle;
 6313: }
 6314: 
 6315: ul.LC_TabContent {
 6316:   display:block;
 6317:   background: $sidebg;
 6318:   border-bottom: solid 1px $lg_border_color;
 6319:   list-style:none;
 6320:   margin: 0 -10px;
 6321:   padding: 0;
 6322: }
 6323: 
 6324: ul.LC_TabContent li,
 6325: ul.LC_TabContentBigger li {
 6326:   float:left;
 6327: }
 6328: 
 6329: ul#LC_secondary_menu li a {
 6330:   color: $fontmenu;
 6331:   text-decoration: none;
 6332: }
 6333: 
 6334: ul.LC_TabContent {
 6335:   min-height:20px;
 6336: }
 6337: 
 6338: ul.LC_TabContent li {
 6339:   vertical-align:middle;
 6340:   padding: 0 16px 0 10px;
 6341:   background-color:$tabbg;
 6342:   border-bottom:solid 1px $lg_border_color;
 6343:   border-right: solid 1px $font;
 6344: }
 6345: 
 6346: ul.LC_TabContent .right {
 6347:   float:right;
 6348: }
 6349: 
 6350: ul.LC_TabContent li a,
 6351: ul.LC_TabContent li {
 6352:   color:rgb(47,47,47);
 6353:   text-decoration:none;
 6354:   font-size:95%;
 6355:   font-weight:bold;
 6356:   min-height:20px;
 6357: }
 6358: 
 6359: ul.LC_TabContent li a:hover,
 6360: ul.LC_TabContent li a:focus {
 6361:   color: $button_hover;
 6362:   background:none;
 6363:   outline:none;
 6364: }
 6365: 
 6366: ul.LC_TabContent li:hover {
 6367:   color: $button_hover;
 6368:   cursor:pointer;
 6369: }
 6370: 
 6371: ul.LC_TabContent li.active {
 6372:   color: $font;
 6373:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6374:   border-bottom:solid 1px #FFFFFF;
 6375:   cursor: default;
 6376: }
 6377: 
 6378: ul.LC_TabContent li.active a {
 6379:   color:$font;
 6380:   background:#FFFFFF;
 6381:   outline: none;
 6382: }
 6383: #maincoursedoc {
 6384:   clear:both;
 6385: }
 6386: 
 6387: ul.LC_TabContentBigger {
 6388:   display:block;
 6389:   list-style:none;
 6390:   padding: 0;
 6391: }
 6392: 
 6393: ul.LC_TabContentBigger li {
 6394:   vertical-align:bottom;
 6395:   height: 30px;
 6396:   font-size:110%;
 6397:   font-weight:bold;
 6398:   color: #737373;
 6399: }
 6400: 
 6401: ul.LC_TabContentBigger li.active {
 6402:   position: relative;
 6403:   top: 1px;
 6404: }
 6405: 
 6406: ul.LC_TabContentBigger li a {
 6407:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6408:   height: 30px;
 6409:   line-height: 30px;
 6410:   text-align: center;
 6411:   display: block;
 6412:   text-decoration: none;
 6413:   outline: none;
 6414: }
 6415: 
 6416: ul.LC_TabContentBigger li.active a {
 6417:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6418:   color:$font;
 6419: }
 6420: 
 6421: ul.LC_TabContentBigger li b {
 6422:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6423:   display: block;
 6424:   float: left;
 6425:   padding: 0 30px;
 6426:   border-bottom: 1px solid $lg_border_color;
 6427: }
 6428: 
 6429: ul.LC_TabContentBigger li:hover b {
 6430:   color:$button_hover;
 6431: }
 6432: 
 6433: ul.LC_TabContentBigger li.active b {
 6434:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6435:   color:$font;
 6436:   border: 0;
 6437:   cursor:default;
 6438: }
 6439: 
 6440: ul.LC_CourseBreadcrumbs {
 6441:   background: $sidebg;
 6442:   line-height: 32px;
 6443:   padding-left: 10px;
 6444:   margin: 0 0 10px 0;
 6445:   list-style-position: inside;
 6446: 
 6447: }
 6448: 
 6449: ol#LC_MenuBreadcrumbs,
 6450: ol#LC_PathBreadcrumbs {
 6451:   padding-left: 10px;
 6452:   margin: 0;
 6453:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6454: }
 6455: 
 6456: ol#LC_MenuBreadcrumbs li,
 6457: ol#LC_PathBreadcrumbs li,
 6458: ul.LC_CourseBreadcrumbs li {
 6459:   display: inline;
 6460:   white-space: normal;  
 6461: }
 6462: 
 6463: ol#LC_MenuBreadcrumbs li a,
 6464: ul.LC_CourseBreadcrumbs li a {
 6465:   text-decoration: none;
 6466:   font-size:90%;
 6467: }
 6468: 
 6469: ol#LC_MenuBreadcrumbs h1 {
 6470:   display: inline;
 6471:   font-size: 90%;
 6472:   line-height: 2.5em;
 6473:   margin: 0;
 6474:   padding: 0;
 6475: }
 6476: 
 6477: ol#LC_PathBreadcrumbs li a {
 6478:   text-decoration:none;
 6479:   font-size:100%;
 6480:   font-weight:bold;
 6481: }
 6482: 
 6483: .LC_Box {
 6484:   border: solid 1px $lg_border_color;
 6485:   padding: 0 10px 10px 10px;
 6486: }
 6487: 
 6488: .LC_AboutMe_Image {
 6489:   float:left;
 6490:   margin-right:10px;
 6491: }
 6492: 
 6493: .LC_Clear_AboutMe_Image {
 6494:   clear:left;
 6495: }
 6496: 
 6497: dl.LC_ListStyleClean dt {
 6498:   padding-right: 5px;
 6499:   display: table-header-group;
 6500: }
 6501: 
 6502: dl.LC_ListStyleClean dd {
 6503:   display: table-row;
 6504: }
 6505: 
 6506: .LC_ListStyleClean,
 6507: .LC_ListStyleSimple,
 6508: .LC_ListStyleNormal,
 6509: .LC_ListStyleSpecial {
 6510:   /* display:block; */
 6511:   list-style-position: inside;
 6512:   list-style-type: none;
 6513:   overflow: hidden;
 6514:   padding: 0;
 6515: }
 6516: 
 6517: .LC_ListStyleSimple li,
 6518: .LC_ListStyleSimple dd,
 6519: .LC_ListStyleNormal li,
 6520: .LC_ListStyleNormal dd,
 6521: .LC_ListStyleSpecial li,
 6522: .LC_ListStyleSpecial dd {
 6523:   margin: 0;
 6524:   padding: 5px 5px 5px 10px;
 6525:   clear: both;
 6526: }
 6527: 
 6528: .LC_ListStyleClean li,
 6529: .LC_ListStyleClean dd {
 6530:   padding-top: 0;
 6531:   padding-bottom: 0;
 6532: }
 6533: 
 6534: .LC_ListStyleSimple dd,
 6535: .LC_ListStyleSimple li {
 6536:   border-bottom: solid 1px $lg_border_color;
 6537: }
 6538: 
 6539: .LC_ListStyleSpecial li,
 6540: .LC_ListStyleSpecial dd {
 6541:   list-style-type: none;
 6542:   background-color: RGB(220, 220, 220);
 6543:   margin-bottom: 4px;
 6544: }
 6545: 
 6546: table.LC_SimpleTable {
 6547:   margin:5px;
 6548:   border:solid 1px $lg_border_color;
 6549: }
 6550: 
 6551: table.LC_SimpleTable tr {
 6552:   padding: 0;
 6553:   border:solid 1px $lg_border_color;
 6554: }
 6555: 
 6556: table.LC_SimpleTable thead {
 6557:   background:rgb(220,220,220);
 6558: }
 6559: 
 6560: div.LC_columnSection {
 6561:   display: block;
 6562:   clear: both;
 6563:   overflow: hidden;
 6564:   margin: 0;
 6565: }
 6566: 
 6567: div.LC_columnSection>* {
 6568:   float: left;
 6569:   margin: 10px 20px 10px 0;
 6570:   overflow:hidden;
 6571: }
 6572: 
 6573: table em {
 6574:   font-weight: bold;
 6575:   font-style: normal;
 6576: }
 6577: 
 6578: table.LC_tableBrowseRes,
 6579: table.LC_tableOfContent {
 6580:   border:none;
 6581:   border-spacing: 1px;
 6582:   padding: 3px;
 6583:   background-color: #FFFFFF;
 6584:   font-size: 90%;
 6585: }
 6586: 
 6587: table.LC_tableOfContent {
 6588:   border-collapse: collapse;
 6589: }
 6590: 
 6591: table.LC_tableBrowseRes a,
 6592: table.LC_tableOfContent a {
 6593:   background-color: transparent;
 6594:   text-decoration: none;
 6595: }
 6596: 
 6597: table.LC_tableOfContent img {
 6598:   border: none;
 6599:   height: 1.3em;
 6600:   vertical-align: text-bottom;
 6601:   margin-right: 0.3em;
 6602: }
 6603: 
 6604: a#LC_content_toolbar_firsthomework {
 6605:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6606: }
 6607: 
 6608: a#LC_content_toolbar_launchnav {
 6609:   background-image:url(/res/adm/pages/start-navigation.gif);
 6610: }
 6611: 
 6612: a#LC_content_toolbar_closenav {
 6613:   background-image:url(/res/adm/pages/close-navigation.gif);
 6614: }
 6615: 
 6616: a#LC_content_toolbar_everything {
 6617:   background-image:url(/res/adm/pages/show-all.gif);
 6618: }
 6619: 
 6620: a#LC_content_toolbar_uncompleted {
 6621:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6622: }
 6623: 
 6624: #LC_content_toolbar_clearbubbles {
 6625:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6626: }
 6627: 
 6628: a#LC_content_toolbar_changefolder {
 6629:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6630: }
 6631: 
 6632: a#LC_content_toolbar_changefolder_toggled {
 6633:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6634: }
 6635: 
 6636: ul#LC_toolbar li a:hover {
 6637:   background-position: bottom center;
 6638: }
 6639: 
 6640: ul#LC_toolbar {
 6641:   padding: 0;
 6642:   margin: 2px;
 6643:   list-style:none;
 6644:   position:relative;
 6645:   background-color:white;
 6646: }
 6647: 
 6648: ul#LC_toolbar li {
 6649:   border:1px solid white;
 6650:   padding: 0;
 6651:   margin: 0;
 6652:   float: left;
 6653:   display:inline;
 6654:   vertical-align:middle;
 6655: }
 6656: 
 6657: 
 6658: a.LC_toolbarItem {
 6659:   display:block;
 6660:   padding: 0;
 6661:   margin: 0;
 6662:   height: 32px;
 6663:   width: 32px;
 6664:   color:white;
 6665:   border: none;
 6666:   background-repeat:no-repeat;
 6667:   background-color:transparent;
 6668: }
 6669: 
 6670: ul.LC_funclist {
 6671:     margin: 0;
 6672:     padding: 0.5em 1em 0.5em 0;
 6673: }
 6674: 
 6675: ul.LC_funclist > li:first-child {
 6676:     font-weight:bold; 
 6677:     margin-left:0.8em;
 6678: }
 6679: 
 6680: ul.LC_funclist + ul.LC_funclist {
 6681:     /* 
 6682:        left border as a seperator if we have more than
 6683:        one list 
 6684:     */
 6685:     border-left: 1px solid $sidebg;
 6686:     /* 
 6687:        this hides the left border behind the border of the 
 6688:        outer box if element is wrapped to the next 'line' 
 6689:     */
 6690:     margin-left: -1px;
 6691: }
 6692: 
 6693: ul.LC_funclist li {
 6694:   display: inline;
 6695:   white-space: nowrap;
 6696:   margin: 0 0 0 25px;
 6697:   line-height: 150%;
 6698: }
 6699: 
 6700: .ui-accordion .LC_advanced_toggle {
 6701:   float: right;
 6702:   font-size: 90%;
 6703:   padding: 0px 4px
 6704: }
 6705: 
 6706: END
 6707: }
 6708: 
 6709: =pod
 6710: 
 6711: =item * &headtag()
 6712: 
 6713: Returns a uniform footer for LON-CAPA web pages.
 6714: 
 6715: Inputs: $title - optional title for the head
 6716:         $head_extra - optional extra HTML to put inside the <head>
 6717:         $args - optional arguments
 6718:             force_register - if is true call registerurl so the remote is 
 6719:                              informed
 6720:             redirect       -> array ref of
 6721:                                    1- seconds before redirect occurs
 6722:                                    2- url to redirect to
 6723:                                    3- whether the side effect should occur
 6724:                            (side effect of setting 
 6725:                                $env{'internal.head.redirect'} to the url 
 6726:                                redirected too)
 6727:             domain         -> force to color decorate a page for a specific
 6728:                                domain
 6729:             function       -> force usage of a specific rolish color scheme
 6730:             bgcolor        -> override the default page bgcolor
 6731:             no_auto_mt_title
 6732:                            -> prevent &mt()ing the title arg
 6733: 
 6734: =cut
 6735: 
 6736: sub headtag {
 6737:     my ($title,$head_extra,$args) = @_;
 6738:     
 6739:     my $function = $args->{'function'} || &get_users_function();
 6740:     my $domain   = $args->{'domain'}   || &determinedomain();
 6741:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6742:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6743: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6744: 		   #time(),
 6745: 		   $env{'environment.color.timestamp'},
 6746: 		   $function,$domain,$bgcolor);
 6747: 
 6748:     $url = '/adm/css/'.&escape($url).'.css';
 6749: 
 6750:     my $result =
 6751: 	'<head>'.
 6752: 	&font_settings();
 6753: 
 6754:     if (!$args->{'frameset'}) {
 6755: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6756:     }
 6757:     if ($args->{'force_register'}) {
 6758: 	$result .= &Apache::lonmenu::registerurl(1);
 6759:     }
 6760:     if (!$args->{'no_nav_bar'} 
 6761: 	&& !$args->{'only_body'}
 6762: 	&& !$args->{'frameset'}) {
 6763: 	$result .= &help_menu_js();
 6764:     }
 6765: 
 6766:     if (ref($args->{'redirect'})) {
 6767: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6768: 	$url = &Apache::lonenc::check_encrypt($url);
 6769: 	if (!$inhibit_continue) {
 6770: 	    $env{'internal.head.redirect'} = $url;
 6771: 	}
 6772: 	$result.=<<ADDMETA
 6773: <meta http-equiv="pragma" content="no-cache" />
 6774: <meta http-equiv="Refresh" content="$time; url=$url" />
 6775: ADDMETA
 6776:     }
 6777:     if (!defined($title)) {
 6778: 	$title = 'The LearningOnline Network with CAPA';
 6779:     }
 6780:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6781:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6782: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6783: 	.$head_extra;
 6784:     return $result;
 6785: }
 6786: 
 6787: =pod
 6788: 
 6789: =item * &font_settings()
 6790: 
 6791: Returns neccessary <meta> to set the proper encoding
 6792: 
 6793: Inputs: none
 6794: 
 6795: =cut
 6796: 
 6797: sub font_settings {
 6798:     my $headerstring='';
 6799:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6800: 	$headerstring.=
 6801: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6802:     }
 6803:     return $headerstring;
 6804: }
 6805: 
 6806: =pod
 6807: 
 6808: =item * &xml_begin()
 6809: 
 6810: Returns the needed doctype and <html>
 6811: 
 6812: Inputs: none
 6813: 
 6814: =cut
 6815: 
 6816: sub xml_begin {
 6817:     my $output='';
 6818: 
 6819:     if ($env{'browser.mathml'}) {
 6820: 	$output='<?xml version="1.0"?>'
 6821:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6822: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6823:             
 6824: #	    .'<!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">] >'
 6825: 	    .'<!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">'
 6826:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6827: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6828:     } else {
 6829: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6830:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6831:     }
 6832:     return $output;
 6833: }
 6834: 
 6835: =pod
 6836: 
 6837: =item * &endheadtag()
 6838: 
 6839: Returns a uniform </head> for LON-CAPA web pages.
 6840: 
 6841: Inputs: none
 6842: 
 6843: =cut
 6844: 
 6845: sub endheadtag {
 6846:     return '</head>';
 6847: }
 6848: 
 6849: =pod
 6850: 
 6851: =item * &head()
 6852: 
 6853: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6854: 
 6855: Inputs:
 6856: 
 6857: =over 4
 6858: 
 6859: $title - optional title for the page
 6860: 
 6861: $head_extra - optional extra HTML to put inside the <head>
 6862: 
 6863: =back
 6864: 
 6865: =cut
 6866: 
 6867: sub head {
 6868:     my ($title,$head_extra,$args) = @_;
 6869:     return &headtag($title,$head_extra,$args).&endheadtag();
 6870: }
 6871: 
 6872: =pod
 6873: 
 6874: =item * &start_page()
 6875: 
 6876: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6877: 
 6878: Inputs:
 6879: 
 6880: =over 4
 6881: 
 6882: $title - optional title for the page
 6883: 
 6884: $head_extra - optional extra HTML to incude inside the <head>
 6885: 
 6886: $args - additional optional args supported are:
 6887: 
 6888: =over 8
 6889: 
 6890:              only_body      -> is true will set &bodytag() onlybodytag
 6891:                                     arg on
 6892:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6893:              add_entries    -> additional attributes to add to the  <body>
 6894:              domain         -> force to color decorate a page for a 
 6895:                                     specific domain
 6896:              function       -> force usage of a specific rolish color
 6897:                                     scheme
 6898:              redirect       -> see &headtag()
 6899:              bgcolor        -> override the default page bg color
 6900:              js_ready       -> return a string ready for being used in 
 6901:                                     a javascript writeln
 6902:              html_encode    -> return a string ready for being used in 
 6903:                                     a html attribute
 6904:              force_register -> if is true will turn on the &bodytag()
 6905:                                     $forcereg arg
 6906:              frameset       -> if true will start with a <frameset>
 6907:                                     rather than <body>
 6908:              skip_phases    -> hash ref of 
 6909:                                     head -> skip the <html><head> generation
 6910:                                     body -> skip all <body> generation
 6911:              no_inline_link -> if true and in remote mode, don't show the 
 6912:                                     'Switch To Inline Menu' link
 6913:              no_auto_mt_title -> prevent &mt()ing the title arg
 6914:              inherit_jsmath -> when creating popup window in a page,
 6915:                                     should it have jsmath forced on by the
 6916:                                     current page
 6917:              bread_crumbs ->             Array containing breadcrumbs
 6918:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 6919: 
 6920: =back
 6921: 
 6922: =back
 6923: 
 6924: =cut
 6925: 
 6926: sub start_page {
 6927:     my ($title,$head_extra,$args) = @_;
 6928:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6929:     my %head_args;
 6930:     foreach my $arg ('redirect','force_register','domain','function',
 6931: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6932: 		     'no_auto_mt_title') {
 6933: 	if (defined($args->{$arg})) {
 6934: 	    $head_args{$arg} = $args->{$arg};
 6935: 	}
 6936:     }
 6937: 
 6938:     $env{'internal.start_page'}++;
 6939:     my $result;
 6940:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6941: 	$result.=
 6942: 	    &xml_begin().
 6943: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6944:     }
 6945:     
 6946:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6947: 	if ($args->{'frameset'}) {
 6948: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6949: 						$args->{'add_entries'});
 6950: 	    $result .= "\n<frameset $attr_string>\n";
 6951:         } else {
 6952:             $result .=
 6953:                 &bodytag($title, 
 6954:                          $args->{'function'},       $args->{'add_entries'},
 6955:                          $args->{'only_body'},      $args->{'domain'},
 6956:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6957:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 6958:                          $args);
 6959:         }
 6960:     }
 6961: 
 6962:     if ($args->{'js_ready'}) {
 6963: 		$result = &js_ready($result);
 6964:     }
 6965:     if ($args->{'html_encode'}) {
 6966: 		$result = &html_encode($result);
 6967:     }
 6968: 
 6969:     # Preparation for new and consistent functionlist at top of screen
 6970:     # if ($args->{'functionlist'}) {
 6971:     #            $result .= &build_functionlist();
 6972:     #}
 6973: 
 6974:     # Don't add anything more if only_body wanted
 6975:     return $result if $args->{'only_body'};
 6976: 
 6977:     #Breadcrumbs for Construction Space provided by &bodytag. 
 6978:     if (($env{'environment.remote'} eq 'off') && ($env{'request.state'} eq 'construct')) {
 6979:         return $result;
 6980:     }
 6981:  
 6982:     #Breadcrumbs
 6983:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6984: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6985: 		#if any br links exists, add them to the breadcrumbs
 6986: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6987: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6988: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6989: 			}
 6990: 		}
 6991: 
 6992: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6993: 		if(exists($args->{'bread_crumbs_component'})){
 6994: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6995: 		}else{
 6996: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6997: 		}
 6998:     }
 6999:     return $result;
 7000: }
 7001: 
 7002: 
 7003: =pod
 7004: 
 7005: =item * &head()
 7006: 
 7007: Returns a complete </body></html> section for LON-CAPA web pages.
 7008: 
 7009: Inputs:         $args - additional optional args supported are:
 7010:                  js_ready     -> return a string ready for being used in 
 7011:                                  a javascript writeln
 7012:                  html_encode  -> return a string ready for being used in 
 7013:                                  a html attribute
 7014:                  frameset     -> if true will start with a <frameset>
 7015:                                  rather than <body>
 7016:                  dicsussion   -> if true will get discussion from
 7017:                                   lonxml::xmlend
 7018:                                  (you can pass the target and parser arguments
 7019:                                   through optional 'target' and 'parser' args
 7020:                                   to this routine)
 7021: 
 7022: =cut
 7023: 
 7024: sub end_page {
 7025:     my ($args) = @_;
 7026:     $env{'internal.end_page'}++;
 7027:     my $result;
 7028:     if ($args->{'discussion'}) {
 7029: 	my ($target,$parser);
 7030: 	if (ref($args->{'discussion'})) {
 7031: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7032: 				$args->{'discussion'}{'parser'});
 7033: 	}
 7034: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7035:     }
 7036: 
 7037:     if ($args->{'frameset'}) {
 7038: 	$result .= '</frameset>';
 7039:     } else {
 7040: 	$result .= &endbodytag($args);
 7041:     }
 7042:     $result .= "\n</html>";
 7043: 
 7044:     if ($args->{'js_ready'}) {
 7045: 	$result = &js_ready($result);
 7046:     }
 7047: 
 7048:     if ($args->{'html_encode'}) {
 7049: 	$result = &html_encode($result);
 7050:     }
 7051: 
 7052:     return $result;
 7053: }
 7054: 
 7055: sub html_encode {
 7056:     my ($result) = @_;
 7057: 
 7058:     $result = &HTML::Entities::encode($result,'<>&"');
 7059:     
 7060:     return $result;
 7061: }
 7062: sub js_ready {
 7063:     my ($result) = @_;
 7064: 
 7065:     $result =~ s/[\n\r]/ /xmsg;
 7066:     $result =~ s/\\/\\\\/xmsg;
 7067:     $result =~ s/'/\\'/xmsg;
 7068:     $result =~ s{</}{<\\/}xmsg;
 7069:     
 7070:     return $result;
 7071: }
 7072: 
 7073: sub validate_page {
 7074:     if (  exists($env{'internal.start_page'})
 7075: 	  &&     $env{'internal.start_page'} > 1) {
 7076: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7077: 				 $env{'internal.start_page'}.' '.
 7078: 				 $ENV{'request.filename'});
 7079:     }
 7080:     if (  exists($env{'internal.end_page'})
 7081: 	  &&     $env{'internal.end_page'} > 1) {
 7082: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7083: 				 $env{'internal.end_page'}.' '.
 7084: 				 $env{'request.filename'});
 7085:     }
 7086:     if (     exists($env{'internal.start_page'})
 7087: 	&& ! exists($env{'internal.end_page'})) {
 7088: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7089: 				 $env{'request.filename'});
 7090:     }
 7091:     if (   ! exists($env{'internal.start_page'})
 7092: 	&&   exists($env{'internal.end_page'})) {
 7093: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7094: 				 $env{'request.filename'});
 7095:     }
 7096: }
 7097: 
 7098: sub simple_error_page {
 7099:     my ($r,$title,$msg) = @_;
 7100:     my $page =
 7101: 	&Apache::loncommon::start_page($title).
 7102: 	&mt($msg).
 7103: 	&Apache::loncommon::end_page();
 7104:     if (ref($r)) {
 7105: 	$r->print($page);
 7106: 	return;
 7107:     }
 7108:     return $page;
 7109: }
 7110: 
 7111: {
 7112:     my @row_count;
 7113: 
 7114:     sub start_data_table_count {
 7115:         unshift(@row_count, 0);
 7116:         return;
 7117:     }
 7118: 
 7119:     sub end_data_table_count {
 7120:         shift(@row_count);
 7121:         return;
 7122:     }
 7123: 
 7124:     sub start_data_table {
 7125: 	my ($add_class) = @_;
 7126: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7127:         &start_data_table_count();
 7128: 	return '<table class="'.$css_class.'">'."\n";
 7129:     }
 7130: 
 7131:     sub end_data_table {
 7132:         &end_data_table_count();
 7133: 	return '</table>'."\n";;
 7134:     }
 7135: 
 7136:     sub start_data_table_row {
 7137: 	my ($add_class) = @_;
 7138: 	$row_count[0]++;
 7139: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7140: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7141: 	return  '<tr class="'.$css_class.'">'."\n";;
 7142:     }
 7143:     
 7144:     sub continue_data_table_row {
 7145: 	my ($add_class) = @_;
 7146: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7147: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7148: 	return  '<tr class="'.$css_class.'">'."\n";;
 7149:     }
 7150: 
 7151:     sub end_data_table_row {
 7152: 	return '</tr>'."\n";;
 7153:     }
 7154: 
 7155:     sub start_data_table_empty_row {
 7156: #	$row_count[0]++;
 7157: 	return  '<tr class="LC_empty_row" >'."\n";;
 7158:     }
 7159: 
 7160:     sub end_data_table_empty_row {
 7161: 	return '</tr>'."\n";;
 7162:     }
 7163: 
 7164:     sub start_data_table_header_row {
 7165: 	return  '<tr class="LC_header_row">'."\n";;
 7166:     }
 7167: 
 7168:     sub end_data_table_header_row {
 7169: 	return '</tr>'."\n";;
 7170:     }
 7171: 
 7172:     sub data_table_caption {
 7173:         my $caption = shift;
 7174:         return "<caption class=\"LC_caption\">$caption</caption>";
 7175:     }
 7176: }
 7177: 
 7178: =pod
 7179: 
 7180: =item * &inhibit_menu_check($arg)
 7181: 
 7182: Checks for a inhibitmenu state and generates output to preserve it
 7183: 
 7184: Inputs:         $arg - can be any of
 7185:                      - undef - in which case the return value is a string 
 7186:                                to add  into arguments list of a uri
 7187:                      - 'input' - in which case the return value is a HTML
 7188:                                  <form> <input> field of type hidden to
 7189:                                  preserve the value
 7190:                      - a url - in which case the return value is the url with
 7191:                                the neccesary cgi args added to preserve the
 7192:                                inhibitmenu state
 7193:                      - a ref to a url - no return value, but the string is
 7194:                                         updated to include the neccessary cgi
 7195:                                         args to preserve the inhibitmenu state
 7196: 
 7197: =cut
 7198: 
 7199: sub inhibit_menu_check {
 7200:     my ($arg) = @_;
 7201:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7202:     if ($arg eq 'input') {
 7203: 	if ($env{'form.inhibitmenu'}) {
 7204: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7205: 	} else {
 7206: 	    return
 7207: 	}
 7208:     }
 7209:     if ($env{'form.inhibitmenu'}) {
 7210: 	if (ref($arg)) {
 7211: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7212: 	} elsif ($arg eq '') {
 7213: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7214: 	} else {
 7215: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7216: 	}
 7217:     }
 7218:     if (!ref($arg)) {
 7219: 	return $arg;
 7220:     }
 7221: }
 7222: 
 7223: ###############################################
 7224: 
 7225: =pod
 7226: 
 7227: =back
 7228: 
 7229: =head1 User Information Routines
 7230: 
 7231: =over 4
 7232: 
 7233: =item * &get_users_function()
 7234: 
 7235: Used by &bodytag to determine the current users primary role.
 7236: Returns either 'student','coordinator','admin', or 'author'.
 7237: 
 7238: =cut
 7239: 
 7240: ###############################################
 7241: sub get_users_function {
 7242:     my $function = 'norole';
 7243:     if ($env{'request.role'}=~/^(st)/) {
 7244:         $function='student';
 7245:     }
 7246:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7247:         $function='coordinator';
 7248:     }
 7249:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7250:         $function='admin';
 7251:     }
 7252:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7253:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 7254:         $function='author';
 7255:     }
 7256:     return $function;
 7257: }
 7258: 
 7259: ###############################################
 7260: 
 7261: =pod
 7262: 
 7263: =item * &show_course()
 7264: 
 7265: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7266: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7267: 
 7268: Inputs:
 7269: None
 7270: 
 7271: Outputs:
 7272: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7273: 
 7274: =cut
 7275: 
 7276: ###############################################
 7277: sub show_course {
 7278:     my $course = !$env{'user.adv'};
 7279:     if (!$env{'user.adv'}) {
 7280:         foreach my $env (keys(%env)) {
 7281:             next if ($env !~ m/^user\.priv\./);
 7282:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7283:                 $course = 0;
 7284:                 last;
 7285:             }
 7286:         }
 7287:     }
 7288:     return $course;
 7289: }
 7290: 
 7291: ###############################################
 7292: 
 7293: =pod
 7294: 
 7295: =item * &check_user_status()
 7296: 
 7297: Determines current status of supplied role for a
 7298: specific user. Roles can be active, previous or future.
 7299: 
 7300: Inputs: 
 7301: user's domain, user's username, course's domain,
 7302: course's number, optional section ID.
 7303: 
 7304: Outputs:
 7305: role status: active, previous or future. 
 7306: 
 7307: =cut
 7308: 
 7309: sub check_user_status {
 7310:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7311:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 7312:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
 7313:     my @uroles = keys %userinfo;
 7314:     my $srchstr;
 7315:     my $active_chk = 'none';
 7316:     my $now = time;
 7317:     if (@uroles > 0) {
 7318:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7319:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7320:         } else {
 7321:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7322:         }
 7323:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7324:             my $role_end = 0;
 7325:             my $role_start = 0;
 7326:             $active_chk = 'active';
 7327:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7328:                 $role_end = $1;
 7329:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7330:                     $role_start = $1;
 7331:                 }
 7332:             }
 7333:             if ($role_start > 0) {
 7334:                 if ($now < $role_start) {
 7335:                     $active_chk = 'future';
 7336:                 }
 7337:             }
 7338:             if ($role_end > 0) {
 7339:                 if ($now > $role_end) {
 7340:                     $active_chk = 'previous';
 7341:                 }
 7342:             }
 7343:         }
 7344:     }
 7345:     return $active_chk;
 7346: }
 7347: 
 7348: ###############################################
 7349: 
 7350: =pod
 7351: 
 7352: =item * &get_sections()
 7353: 
 7354: Determines all the sections for a course including
 7355: sections with students and sections containing other roles.
 7356: Incoming parameters: 
 7357: 
 7358: 1. domain
 7359: 2. course number 
 7360: 3. reference to array containing roles for which sections should 
 7361: be gathered (optional).
 7362: 4. reference to array containing status types for which sections 
 7363: should be gathered (optional).
 7364: 
 7365: If the third argument is undefined, sections are gathered for any role. 
 7366: If the fourth argument is undefined, sections are gathered for any status.
 7367: Permissible values are 'active' or 'future' or 'previous'.
 7368:  
 7369: Returns section hash (keys are section IDs, values are
 7370: number of users in each section), subject to the
 7371: optional roles filter, optional status filter 
 7372: 
 7373: =cut
 7374: 
 7375: ###############################################
 7376: sub get_sections {
 7377:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7378:     if (!defined($cdom) || !defined($cnum)) {
 7379:         my $cid =  $env{'request.course.id'};
 7380: 
 7381: 	return if (!defined($cid));
 7382: 
 7383:         $cdom = $env{'course.'.$cid.'.domain'};
 7384:         $cnum = $env{'course.'.$cid.'.num'};
 7385:     }
 7386: 
 7387:     my %sectioncount;
 7388:     my $now = time;
 7389: 
 7390:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7391: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7392: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7393: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7394:         my $start_index = &Apache::loncoursedata::CL_START();
 7395:         my $end_index = &Apache::loncoursedata::CL_END();
 7396:         my $status;
 7397: 	while (my ($student,$data) = each(%$classlist)) {
 7398: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7399: 				                     $data->[$status_index],
 7400:                                                      $data->[$start_index],
 7401:                                                      $data->[$end_index]);
 7402:             if ($stu_status eq 'Active') {
 7403:                 $status = 'active';
 7404:             } elsif ($end < $now) {
 7405:                 $status = 'previous';
 7406:             } elsif ($start > $now) {
 7407:                 $status = 'future';
 7408:             } 
 7409: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7410:                 if ((!defined($possible_status)) || (($status ne '') && 
 7411:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7412: 		    $sectioncount{$section}++;
 7413:                 }
 7414: 	    }
 7415: 	}
 7416:     }
 7417:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7418:     foreach my $user (sort(keys(%courseroles))) {
 7419: 	if ($user !~ /^(\w{2})/) { next; }
 7420: 	my ($role) = ($user =~ /^(\w{2})/);
 7421: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7422: 	my ($section,$status);
 7423: 	if ($role eq 'cr' &&
 7424: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7425: 	    $section=$1;
 7426: 	}
 7427: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7428: 	if (!defined($section) || $section eq '-1') { next; }
 7429:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7430:         if ($end == -1 && $start == -1) {
 7431:             next; #deleted role
 7432:         }
 7433:         if (!defined($possible_status)) { 
 7434:             $sectioncount{$section}++;
 7435:         } else {
 7436:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7437:                 $status = 'active';
 7438:             } elsif ($end < $now) {
 7439:                 $status = 'future';
 7440:             } elsif ($start > $now) {
 7441:                 $status = 'previous';
 7442:             }
 7443:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7444:                 $sectioncount{$section}++;
 7445:             }
 7446:         }
 7447:     }
 7448:     return %sectioncount;
 7449: }
 7450: 
 7451: ###############################################
 7452: 
 7453: =pod
 7454: 
 7455: =item * &get_course_users()
 7456: 
 7457: Retrieves usernames:domains for users in the specified course
 7458: with specific role(s), and access status. 
 7459: 
 7460: Incoming parameters:
 7461: 1. course domain
 7462: 2. course number
 7463: 3. access status: users must have - either active, 
 7464: previous, future, or all.
 7465: 4. reference to array of permissible roles
 7466: 5. reference to array of section restrictions (optional)
 7467: 6. reference to results object (hash of hashes).
 7468: 7. reference to optional userdata hash
 7469: 8. reference to optional statushash
 7470: 9. flag if privileged users (except those set to unhide in
 7471:    course settings) should be excluded    
 7472: Keys of top level results hash are roles.
 7473: Keys of inner hashes are username:domain, with 
 7474: values set to access type.
 7475: Optional userdata hash returns an array with arguments in the 
 7476: same order as loncoursedata::get_classlist() for student data.
 7477: 
 7478: Optional statushash returns
 7479: 
 7480: Entries for end, start, section and status are blank because
 7481: of the possibility of multiple values for non-student roles.
 7482: 
 7483: =cut
 7484: 
 7485: ###############################################
 7486: 
 7487: sub get_course_users {
 7488:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7489:     my %idx = ();
 7490:     my %seclists;
 7491: 
 7492:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7493:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7494:     $idx{end} = &Apache::loncoursedata::CL_END();
 7495:     $idx{start} = &Apache::loncoursedata::CL_START();
 7496:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7497:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7498:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7499:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7500: 
 7501:     if (grep(/^st$/,@{$roles})) {
 7502:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7503:         my $now = time;
 7504:         foreach my $student (keys(%{$classlist})) {
 7505:             my $match = 0;
 7506:             my $secmatch = 0;
 7507:             my $section = $$classlist{$student}[$idx{section}];
 7508:             my $status = $$classlist{$student}[$idx{status}];
 7509:             if ($section eq '') {
 7510:                 $section = 'none';
 7511:             }
 7512:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7513:                 if (grep(/^all$/,@{$sections})) {
 7514:                     $secmatch = 1;
 7515:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7516:                     if (grep(/^none$/,@{$sections})) {
 7517:                         $secmatch = 1;
 7518:                     }
 7519:                 } else {  
 7520: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7521: 		        $secmatch = 1;
 7522:                     }
 7523: 		}
 7524:                 if (!$secmatch) {
 7525:                     next;
 7526:                 }
 7527:             }
 7528:             if (defined($$types{'active'})) {
 7529:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7530:                     push(@{$$users{st}{$student}},'active');
 7531:                     $match = 1;
 7532:                 }
 7533:             }
 7534:             if (defined($$types{'previous'})) {
 7535:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7536:                     push(@{$$users{st}{$student}},'previous');
 7537:                     $match = 1;
 7538:                 }
 7539:             }
 7540:             if (defined($$types{'future'})) {
 7541:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7542:                     push(@{$$users{st}{$student}},'future');
 7543:                     $match = 1;
 7544:                 }
 7545:             }
 7546:             if ($match) {
 7547:                 push(@{$seclists{$student}},$section);
 7548:                 if (ref($userdata) eq 'HASH') {
 7549:                     $$userdata{$student} = $$classlist{$student};
 7550:                 }
 7551:                 if (ref($statushash) eq 'HASH') {
 7552:                     $statushash->{$student}{'st'}{$section} = $status;
 7553:                 }
 7554:             }
 7555:         }
 7556:     }
 7557:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7558:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7559:         my $now = time;
 7560:         my %displaystatus = ( previous => 'Expired',
 7561:                               active   => 'Active',
 7562:                               future   => 'Future',
 7563:                             );
 7564:         my %nothide;
 7565:         if ($hidepriv) {
 7566:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7567:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7568:                 if ($user !~ /:/) {
 7569:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7570:                 } else {
 7571:                     $nothide{$user} = 1;
 7572:                 }
 7573:             }
 7574:         }
 7575:         foreach my $person (sort(keys(%coursepersonnel))) {
 7576:             my $match = 0;
 7577:             my $secmatch = 0;
 7578:             my $status;
 7579:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7580:             $user =~ s/:$//;
 7581:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7582:             if ($end == -1 || $start == -1) {
 7583:                 next;
 7584:             }
 7585:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7586:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7587:                 my ($uname,$udom) = split(/:/,$user);
 7588:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7589:                     if (grep(/^all$/,@{$sections})) {
 7590:                         $secmatch = 1;
 7591:                     } elsif ($usec eq '') {
 7592:                         if (grep(/^none$/,@{$sections})) {
 7593:                             $secmatch = 1;
 7594:                         }
 7595:                     } else {
 7596:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7597:                             $secmatch = 1;
 7598:                         }
 7599:                     }
 7600:                     if (!$secmatch) {
 7601:                         next;
 7602:                     }
 7603:                 }
 7604:                 if ($usec eq '') {
 7605:                     $usec = 'none';
 7606:                 }
 7607:                 if ($uname ne '' && $udom ne '') {
 7608:                     if ($hidepriv) {
 7609:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7610:                             (!$nothide{$uname.':'.$udom})) {
 7611:                             next;
 7612:                         }
 7613:                     }
 7614:                     if ($end > 0 && $end < $now) {
 7615:                         $status = 'previous';
 7616:                     } elsif ($start > $now) {
 7617:                         $status = 'future';
 7618:                     } else {
 7619:                         $status = 'active';
 7620:                     }
 7621:                     foreach my $type (keys(%{$types})) { 
 7622:                         if ($status eq $type) {
 7623:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7624:                                 push(@{$$users{$role}{$user}},$type);
 7625:                             }
 7626:                             $match = 1;
 7627:                         }
 7628:                     }
 7629:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7630:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7631: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7632:                         }
 7633:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7634:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7635:                         }
 7636:                         if (ref($statushash) eq 'HASH') {
 7637:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7638:                         }
 7639:                     }
 7640:                 }
 7641:             }
 7642:         }
 7643:         if (grep(/^ow$/,@{$roles})) {
 7644:             if ((defined($cdom)) && (defined($cnum))) {
 7645:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7646:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7647:                     my $owner = $csettings{'internal.courseowner'};
 7648:                     next if ($owner eq '');
 7649:                     my ($ownername,$ownerdom);
 7650:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7651:                         $ownername = $1;
 7652:                         $ownerdom = $2;
 7653:                     } else {
 7654:                         $ownername = $owner;
 7655:                         $ownerdom = $cdom;
 7656:                         $owner = $ownername.':'.$ownerdom;
 7657:                     }
 7658:                     @{$$users{'ow'}{$owner}} = 'any';
 7659:                     if (defined($userdata) && 
 7660: 			!exists($$userdata{$owner})) {
 7661: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7662:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7663:                             push(@{$seclists{$owner}},'none');
 7664:                         }
 7665:                         if (ref($statushash) eq 'HASH') {
 7666:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7667:                         }
 7668: 		    }
 7669:                 }
 7670:             }
 7671:         }
 7672:         foreach my $user (keys(%seclists)) {
 7673:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7674:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7675:         }
 7676:     }
 7677:     return;
 7678: }
 7679: 
 7680: sub get_user_info {
 7681:     my ($udom,$uname,$idx,$userdata) = @_;
 7682:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7683: 	&plainname($uname,$udom,'lastname');
 7684:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7685:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7686:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7687:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7688:     return;
 7689: }
 7690: 
 7691: ###############################################
 7692: 
 7693: =pod
 7694: 
 7695: =item * &get_user_quota()
 7696: 
 7697: Retrieves quota assigned for storage of portfolio files for a user  
 7698: 
 7699: Incoming parameters:
 7700: 1. user's username
 7701: 2. user's domain
 7702: 
 7703: Returns:
 7704: 1. Disk quota (in Mb) assigned to student.
 7705: 2. (Optional) Type of setting: custom or default
 7706:    (individually assigned or default for user's 
 7707:    institutional status).
 7708: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7709:    or student - types as defined in localenroll::inst_usertypes 
 7710:    for user's domain, which determines default quota for user.
 7711: 4. (Optional) - Default quota which would apply to the user.
 7712: 
 7713: If a value has been stored in the user's environment, 
 7714: it will return that, otherwise it returns the maximal default
 7715: defined for the user's instituional status(es) in the domain.
 7716: 
 7717: =cut
 7718: 
 7719: ###############################################
 7720: 
 7721: 
 7722: sub get_user_quota {
 7723:     my ($uname,$udom) = @_;
 7724:     my ($quota,$quotatype,$settingstatus,$defquota);
 7725:     if (!defined($udom)) {
 7726:         $udom = $env{'user.domain'};
 7727:     }
 7728:     if (!defined($uname)) {
 7729:         $uname = $env{'user.name'};
 7730:     }
 7731:     if (($udom eq '' || $uname eq '') ||
 7732:         ($udom eq 'public') && ($uname eq 'public')) {
 7733:         $quota = 0;
 7734:         $quotatype = 'default';
 7735:         $defquota = 0; 
 7736:     } else {
 7737:         my $inststatus;
 7738:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7739:             $quota = $env{'environment.portfolioquota'};
 7740:             $inststatus = $env{'environment.inststatus'};
 7741:         } else {
 7742:             my %userenv = 
 7743:                 &Apache::lonnet::get('environment',['portfolioquota',
 7744:                                      'inststatus'],$udom,$uname);
 7745:             my ($tmp) = keys(%userenv);
 7746:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7747:                 $quota = $userenv{'portfolioquota'};
 7748:                 $inststatus = $userenv{'inststatus'};
 7749:             } else {
 7750:                 undef(%userenv);
 7751:             }
 7752:         }
 7753:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7754:         if ($quota eq '') {
 7755:             $quota = $defquota;
 7756:             $quotatype = 'default';
 7757:         } else {
 7758:             $quotatype = 'custom';
 7759:         }
 7760:     }
 7761:     if (wantarray) {
 7762:         return ($quota,$quotatype,$settingstatus,$defquota);
 7763:     } else {
 7764:         return $quota;
 7765:     }
 7766: }
 7767: 
 7768: ###############################################
 7769: 
 7770: =pod
 7771: 
 7772: =item * &default_quota()
 7773: 
 7774: Retrieves default quota assigned for storage of user portfolio files,
 7775: given an (optional) user's institutional status.
 7776: 
 7777: Incoming parameters:
 7778: 1. domain
 7779: 2. (Optional) institutional status(es).  This is a : separated list of 
 7780:    status types (e.g., faculty, staff, student etc.)
 7781:    which apply to the user for whom the default is being retrieved.
 7782:    If the institutional status string in undefined, the domain
 7783:    default quota will be returned. 
 7784: 
 7785: Returns:
 7786: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7787: 2. (Optional) institutional type which determined the value of the
 7788:    default quota.
 7789: 
 7790: If a value has been stored in the domain's configuration db,
 7791: it will return that, otherwise it returns 20 (for backwards 
 7792: compatibility with domains which have not set up a configuration
 7793: db file; the original statically defined portfolio quota was 20 Mb). 
 7794: 
 7795: If the user's status includes multiple types (e.g., staff and student),
 7796: the largest default quota which applies to the user determines the
 7797: default quota returned.
 7798: 
 7799: =back
 7800: 
 7801: =cut
 7802: 
 7803: ###############################################
 7804: 
 7805: 
 7806: sub default_quota {
 7807:     my ($udom,$inststatus) = @_;
 7808:     my ($defquota,$settingstatus);
 7809:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7810:                                             ['quotas'],$udom);
 7811:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7812:         if ($inststatus ne '') {
 7813:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7814:             foreach my $item (@statuses) {
 7815:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7816:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7817:                         if ($defquota eq '') {
 7818:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7819:                             $settingstatus = $item;
 7820:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7821:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7822:                             $settingstatus = $item;
 7823:                         }
 7824:                     }
 7825:                 } else {
 7826:                     if ($quotahash{'quotas'}{$item} ne '') {
 7827:                         if ($defquota eq '') {
 7828:                             $defquota = $quotahash{'quotas'}{$item};
 7829:                             $settingstatus = $item;
 7830:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7831:                             $defquota = $quotahash{'quotas'}{$item};
 7832:                             $settingstatus = $item;
 7833:                         }
 7834:                     }
 7835:                 }
 7836:             }
 7837:         }
 7838:         if ($defquota eq '') {
 7839:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7840:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7841:             } else {
 7842:                 $defquota = $quotahash{'quotas'}{'default'};
 7843:             }
 7844:             $settingstatus = 'default';
 7845:         }
 7846:     } else {
 7847:         $settingstatus = 'default';
 7848:         $defquota = 20;
 7849:     }
 7850:     if (wantarray) {
 7851:         return ($defquota,$settingstatus);
 7852:     } else {
 7853:         return $defquota;
 7854:     }
 7855: }
 7856: 
 7857: sub get_secgrprole_info {
 7858:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7859:     my %sections_count = &get_sections($cdom,$cnum);
 7860:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7861:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7862:     my @groups = sort(keys(%curr_groups));
 7863:     my $allroles = [];
 7864:     my $rolehash;
 7865:     my $accesshash = {
 7866:                      active => 'Currently has access',
 7867:                      future => 'Will have future access',
 7868:                      previous => 'Previously had access',
 7869:                   };
 7870:     if ($needroles) {
 7871:         $rolehash = {'all' => 'all'};
 7872:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7873: 	if (&Apache::lonnet::error(%user_roles)) {
 7874: 	    undef(%user_roles);
 7875: 	}
 7876:         foreach my $item (keys(%user_roles)) {
 7877:             my ($role)=split(/\:/,$item,2);
 7878:             if ($role eq 'cr') { next; }
 7879:             if ($role =~ /^cr/) {
 7880:                 $$rolehash{$role} = (split('/',$role))[3];
 7881:             } else {
 7882:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7883:             }
 7884:         }
 7885:         foreach my $key (sort(keys(%{$rolehash}))) {
 7886:             push(@{$allroles},$key);
 7887:         }
 7888:         push (@{$allroles},'st');
 7889:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7890:     }
 7891:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7892: }
 7893: 
 7894: sub user_picker {
 7895:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 7896:     my $currdom = $dom;
 7897:     my %curr_selected = (
 7898:                         srchin => 'dom',
 7899:                         srchby => 'lastname',
 7900:                       );
 7901:     my $srchterm;
 7902:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7903:         if ($srch->{'srchby'} ne '') {
 7904:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7905:         }
 7906:         if ($srch->{'srchin'} ne '') {
 7907:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7908:         }
 7909:         if ($srch->{'srchtype'} ne '') {
 7910:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7911:         }
 7912:         if ($srch->{'srchdomain'} ne '') {
 7913:             $currdom = $srch->{'srchdomain'};
 7914:         }
 7915:         $srchterm = $srch->{'srchterm'};
 7916:     }
 7917:     my %lt=&Apache::lonlocal::texthash(
 7918:                     'usr'       => 'Search criteria',
 7919:                     'doma'      => 'Domain/institution to search',
 7920:                     'uname'     => 'username',
 7921:                     'lastname'  => 'last name',
 7922:                     'lastfirst' => 'last name, first name',
 7923:                     'crs'       => 'in this course',
 7924:                     'dom'       => 'in selected LON-CAPA domain', 
 7925:                     'alc'       => 'all LON-CAPA',
 7926:                     'instd'     => 'in institutional directory for selected domain',
 7927:                     'exact'     => 'is',
 7928:                     'contains'  => 'contains',
 7929:                     'begins'    => 'begins with',
 7930:                     'youm'      => "You must include some text to search for.",
 7931:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7932:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7933:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7934:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7935:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7936:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7937:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7938:                                        );
 7939:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7940:     my $srchinsel = ' <select name="srchin">';
 7941: 
 7942:     my @srchins = ('crs','dom','alc','instd');
 7943: 
 7944:     foreach my $option (@srchins) {
 7945:         # FIXME 'alc' option unavailable until 
 7946:         #       loncreateuser::print_user_query_page()
 7947:         #       has been completed.
 7948:         next if ($option eq 'alc');
 7949:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7950:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7951:         if ($curr_selected{'srchin'} eq $option) {
 7952:             $srchinsel .= ' 
 7953:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7954:         } else {
 7955:             $srchinsel .= '
 7956:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7957:         }
 7958:     }
 7959:     $srchinsel .= "\n  </select>\n";
 7960: 
 7961:     my $srchbysel =  ' <select name="srchby">';
 7962:     foreach my $option ('lastname','lastfirst','uname') {
 7963:         if ($curr_selected{'srchby'} eq $option) {
 7964:             $srchbysel .= '
 7965:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7966:         } else {
 7967:             $srchbysel .= '
 7968:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7969:          }
 7970:     }
 7971:     $srchbysel .= "\n  </select>\n";
 7972: 
 7973:     my $srchtypesel = ' <select name="srchtype">';
 7974:     foreach my $option ('begins','contains','exact') {
 7975:         if ($curr_selected{'srchtype'} eq $option) {
 7976:             $srchtypesel .= '
 7977:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7978:         } else {
 7979:             $srchtypesel .= '
 7980:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7981:         }
 7982:     }
 7983:     $srchtypesel .= "\n  </select>\n";
 7984: 
 7985:     my ($newuserscript,$new_user_create);
 7986:     my $context_dom = $env{'request.role.domain'};
 7987:     if ($context eq 'requestcrs') {
 7988:         if ($env{'form.coursedom'} ne '') {
 7989:             $context_dom = $env{'form.coursedom'};
 7990:         }
 7991:     }
 7992:     if ($forcenewuser) {
 7993:         if (ref($srch) eq 'HASH') {
 7994:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 7995:                 if ($cancreate) {
 7996:                     $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>';
 7997:                 } else {
 7998:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7999:                     my %usertypetext = (
 8000:                         official   => 'institutional',
 8001:                         unofficial => 'non-institutional',
 8002:                     );
 8003:                     $new_user_create = '<p class="LC_warning">'
 8004:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8005:                                       .' '
 8006:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8007:                                           ,'<a href="'.$helplink.'">','</a>')
 8008:                                       .'</p><br />';
 8009:                 }
 8010:             }
 8011:         }
 8012: 
 8013:         $newuserscript = <<"ENDSCRIPT";
 8014: 
 8015: function setSearch(createnew,callingForm) {
 8016:     if (createnew == 1) {
 8017:         for (var i=0; i<callingForm.srchby.length; i++) {
 8018:             if (callingForm.srchby.options[i].value == 'uname') {
 8019:                 callingForm.srchby.selectedIndex = i;
 8020:             }
 8021:         }
 8022:         for (var i=0; i<callingForm.srchin.length; i++) {
 8023:             if ( callingForm.srchin.options[i].value == 'dom') {
 8024: 		callingForm.srchin.selectedIndex = i;
 8025:             }
 8026:         }
 8027:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8028:             if (callingForm.srchtype.options[i].value == 'exact') {
 8029:                 callingForm.srchtype.selectedIndex = i;
 8030:             }
 8031:         }
 8032:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8033:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8034:                 callingForm.srchdomain.selectedIndex = i;
 8035:             }
 8036:         }
 8037:     }
 8038: }
 8039: ENDSCRIPT
 8040: 
 8041:     }
 8042: 
 8043:     my $output = <<"END_BLOCK";
 8044: <script type="text/javascript">
 8045: // <![CDATA[
 8046: function validateEntry(callingForm) {
 8047: 
 8048:     var checkok = 1;
 8049:     var srchin;
 8050:     for (var i=0; i<callingForm.srchin.length; i++) {
 8051: 	if ( callingForm.srchin[i].checked ) {
 8052: 	    srchin = callingForm.srchin[i].value;
 8053: 	}
 8054:     }
 8055: 
 8056:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8057:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8058:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8059:     var srchterm =  callingForm.srchterm.value;
 8060:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8061:     var msg = "";
 8062: 
 8063:     if (srchterm == "") {
 8064:         checkok = 0;
 8065:         msg += "$lt{'youm'}\\n";
 8066:     }
 8067: 
 8068:     if (srchtype== 'begins') {
 8069:         if (srchterm.length < 2) {
 8070:             checkok = 0;
 8071:             msg += "$lt{'thte'}\\n";
 8072:         }
 8073:     }
 8074: 
 8075:     if (srchtype== 'contains') {
 8076:         if (srchterm.length < 3) {
 8077:             checkok = 0;
 8078:             msg += "$lt{'thet'}\\n";
 8079:         }
 8080:     }
 8081:     if (srchin == 'instd') {
 8082:         if (srchdomain == '') {
 8083:             checkok = 0;
 8084:             msg += "$lt{'yomc'}\\n";
 8085:         }
 8086:     }
 8087:     if (srchin == 'dom') {
 8088:         if (srchdomain == '') {
 8089:             checkok = 0;
 8090:             msg += "$lt{'ymcd'}\\n";
 8091:         }
 8092:     }
 8093:     if (srchby == 'lastfirst') {
 8094:         if (srchterm.indexOf(",") == -1) {
 8095:             checkok = 0;
 8096:             msg += "$lt{'whus'}\\n";
 8097:         }
 8098:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8099:             checkok = 0;
 8100:             msg += "$lt{'whse'}\\n";
 8101:         }
 8102:     }
 8103:     if (checkok == 0) {
 8104:         alert("$lt{'thfo'}\\n"+msg);
 8105:         return;
 8106:     }
 8107:     if (checkok == 1) {
 8108:         callingForm.submit();
 8109:     }
 8110: }
 8111: 
 8112: $newuserscript
 8113: 
 8114: // ]]>
 8115: </script>
 8116: 
 8117: $new_user_create
 8118: 
 8119: END_BLOCK
 8120: 
 8121:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8122:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8123:                $domform.
 8124:                &Apache::lonhtmlcommon::row_closure().
 8125:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8126:                $srchbysel.
 8127:                $srchtypesel. 
 8128:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8129:                $srchinsel.
 8130:                &Apache::lonhtmlcommon::row_closure(1). 
 8131:                &Apache::lonhtmlcommon::end_pick_box().
 8132:                '<br />';
 8133:     return $output;
 8134: }
 8135: 
 8136: sub user_rule_check {
 8137:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8138:     my $response;
 8139:     if (ref($usershash) eq 'HASH') {
 8140:         foreach my $user (keys(%{$usershash})) {
 8141:             my ($uname,$udom) = split(/:/,$user);
 8142:             next if ($udom eq '' || $uname eq '');
 8143:             my ($id,$newuser);
 8144:             if (ref($usershash->{$user}) eq 'HASH') {
 8145:                 $newuser = $usershash->{$user}->{'newuser'};
 8146:                 $id = $usershash->{$user}->{'id'};
 8147:             }
 8148:             my $inst_response;
 8149:             if (ref($checks) eq 'HASH') {
 8150:                 if (defined($checks->{'username'})) {
 8151:                     ($inst_response,%{$inst_results->{$user}}) = 
 8152:                         &Apache::lonnet::get_instuser($udom,$uname);
 8153:                 } elsif (defined($checks->{'id'})) {
 8154:                     ($inst_response,%{$inst_results->{$user}}) =
 8155:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8156:                 }
 8157:             } else {
 8158:                 ($inst_response,%{$inst_results->{$user}}) =
 8159:                     &Apache::lonnet::get_instuser($udom,$uname);
 8160:                 return;
 8161:             }
 8162:             if (!$got_rules->{$udom}) {
 8163:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8164:                                                   ['usercreation'],$udom);
 8165:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8166:                     foreach my $item ('username','id') {
 8167:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8168:                             $$curr_rules{$udom}{$item} = 
 8169:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8170:                         }
 8171:                     }
 8172:                 }
 8173:                 $got_rules->{$udom} = 1;  
 8174:             }
 8175:             foreach my $item (keys(%{$checks})) {
 8176:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8177:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8178:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8179:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8180:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8181:                                 if ($rule_check{$rule}) {
 8182:                                     $$rulematch{$user}{$item} = $rule;
 8183:                                     if ($inst_response eq 'ok') {
 8184:                                         if (ref($inst_results) eq 'HASH') {
 8185:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8186:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8187:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8188:                                                 }
 8189:                                             }
 8190:                                         }
 8191:                                     }
 8192:                                     last;
 8193:                                 }
 8194:                             }
 8195:                         }
 8196:                     }
 8197:                 }
 8198:             }
 8199:         }
 8200:     }
 8201:     return;
 8202: }
 8203: 
 8204: sub user_rule_formats {
 8205:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8206:     my %text = ( 
 8207:                  'username' => 'Usernames',
 8208:                  'id'       => 'IDs',
 8209:                );
 8210:     my $output;
 8211:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8212:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8213:         if (@{$ruleorder} > 0) {
 8214:             $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>';
 8215:             foreach my $rule (@{$ruleorder}) {
 8216:                 if (ref($curr_rules) eq 'ARRAY') {
 8217:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8218:                         if (ref($rules->{$rule}) eq 'HASH') {
 8219:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8220:                                         $rules->{$rule}{'desc'}.'</li>';
 8221:                         }
 8222:                     }
 8223:                 }
 8224:             }
 8225:             $output .= '</ul>';
 8226:         }
 8227:     }
 8228:     return $output;
 8229: }
 8230: 
 8231: sub instrule_disallow_msg {
 8232:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8233:     my $response;
 8234:     my %text = (
 8235:                   item   => 'username',
 8236:                   items  => 'usernames',
 8237:                   match  => 'matches',
 8238:                   do     => 'does',
 8239:                   action => 'a username',
 8240:                   one    => 'one',
 8241:                );
 8242:     if ($count > 1) {
 8243:         $text{'item'} = 'usernames';
 8244:         $text{'match'} ='match';
 8245:         $text{'do'} = 'do';
 8246:         $text{'action'} = 'usernames',
 8247:         $text{'one'} = 'ones';
 8248:     }
 8249:     if ($checkitem eq 'id') {
 8250:         $text{'items'} = 'IDs';
 8251:         $text{'item'} = 'ID';
 8252:         $text{'action'} = 'an ID';
 8253:         if ($count > 1) {
 8254:             $text{'item'} = 'IDs';
 8255:             $text{'action'} = 'IDs';
 8256:         }
 8257:     }
 8258:     $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 />';
 8259:     if ($mode eq 'upload') {
 8260:         if ($checkitem eq 'username') {
 8261:             $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'}.");
 8262:         } elsif ($checkitem eq 'id') {
 8263:             $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.");
 8264:         }
 8265:     } elsif ($mode eq 'selfcreate') {
 8266:         if ($checkitem eq 'id') {
 8267:             $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.");
 8268:         }
 8269:     } else {
 8270:         if ($checkitem eq 'username') {
 8271:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8272:         } elsif ($checkitem eq 'id') {
 8273:             $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.");
 8274:         }
 8275:     }
 8276:     return $response;
 8277: }
 8278: 
 8279: sub personal_data_fieldtitles {
 8280:     my %fieldtitles = &Apache::lonlocal::texthash (
 8281:                         id => 'Student/Employee ID',
 8282:                         permanentemail => 'E-mail address',
 8283:                         lastname => 'Last Name',
 8284:                         firstname => 'First Name',
 8285:                         middlename => 'Middle Name',
 8286:                         generation => 'Generation',
 8287:                         gen => 'Generation',
 8288:                         inststatus => 'Affiliation',
 8289:                    );
 8290:     return %fieldtitles;
 8291: }
 8292: 
 8293: sub sorted_inst_types {
 8294:     my ($dom) = @_;
 8295:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8296:     my $othertitle = &mt('All users');
 8297:     if ($env{'request.course.id'}) {
 8298:         $othertitle  = &mt('Any users');
 8299:     }
 8300:     my @types;
 8301:     if (ref($order) eq 'ARRAY') {
 8302:         @types = @{$order};
 8303:     }
 8304:     if (@types == 0) {
 8305:         if (ref($usertypes) eq 'HASH') {
 8306:             @types = sort(keys(%{$usertypes}));
 8307:         }
 8308:     }
 8309:     if (keys(%{$usertypes}) > 0) {
 8310:         $othertitle = &mt('Other users');
 8311:     }
 8312:     return ($othertitle,$usertypes,\@types);
 8313: }
 8314: 
 8315: sub get_institutional_codes {
 8316:     my ($settings,$allcourses,$LC_code) = @_;
 8317: # Get complete list of course sections to update
 8318:     my @currsections = ();
 8319:     my @currxlists = ();
 8320:     my $coursecode = $$settings{'internal.coursecode'};
 8321: 
 8322:     if ($$settings{'internal.sectionnums'} ne '') {
 8323:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8324:     }
 8325: 
 8326:     if ($$settings{'internal.crosslistings'} ne '') {
 8327:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8328:     }
 8329: 
 8330:     if (@currxlists > 0) {
 8331:         foreach (@currxlists) {
 8332:             if (m/^([^:]+):(\w*)$/) {
 8333:                 unless (grep/^$1$/,@{$allcourses}) {
 8334:                     push @{$allcourses},$1;
 8335:                     $$LC_code{$1} = $2;
 8336:                 }
 8337:             }
 8338:         }
 8339:     }
 8340:  
 8341:     if (@currsections > 0) {
 8342:         foreach (@currsections) {
 8343:             if (m/^(\w+):(\w*)$/) {
 8344:                 my $sec = $coursecode.$1;
 8345:                 my $lc_sec = $2;
 8346:                 unless (grep/^$sec$/,@{$allcourses}) {
 8347:                     push @{$allcourses},$sec;
 8348:                     $$LC_code{$sec} = $lc_sec;
 8349:                 }
 8350:             }
 8351:         }
 8352:     }
 8353:     return;
 8354: }
 8355: 
 8356: sub get_standard_codeitems {
 8357:     return ('Year','Semester','Department','Number','Section');
 8358: }
 8359: 
 8360: =pod
 8361: 
 8362: =head1 Slot Helpers
 8363: 
 8364: =over 4
 8365: 
 8366: =item * sorted_slots()
 8367: 
 8368: Sorts an array of slot names in order of slot start time (earliest first). 
 8369: 
 8370: Inputs:
 8371: 
 8372: =over 4
 8373: 
 8374: slotsarr  - Reference to array of unsorted slot names.
 8375: 
 8376: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8377: 
 8378: =back
 8379: 
 8380: Returns:
 8381: 
 8382: =over 4
 8383: 
 8384: sorted   - An array of slot names sorted by the start time of the slot.
 8385: 
 8386: =back
 8387: 
 8388: =back
 8389: 
 8390: =cut
 8391: 
 8392: 
 8393: sub sorted_slots {
 8394:     my ($slotsarr,$slots) = @_;
 8395:     my @sorted;
 8396:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8397:         @sorted =
 8398:             sort {
 8399:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8400:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8401:                      }
 8402:                      if (ref($slots->{$a})) { return -1;}
 8403:                      if (ref($slots->{$b})) { return 1;}
 8404:                      return 0;
 8405:                  } @{$slotsarr};
 8406:     }
 8407:     return @sorted;
 8408: }
 8409: 
 8410: 
 8411: =pod
 8412: 
 8413: =head1 HTTP Helpers
 8414: 
 8415: =over 4
 8416: 
 8417: =item * &get_unprocessed_cgi($query,$possible_names)
 8418: 
 8419: Modify the %env hash to contain unprocessed CGI form parameters held in
 8420: $query.  The parameters listed in $possible_names (an array reference),
 8421: will be set in $env{'form.name'} if they do not already exist.
 8422: 
 8423: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8424: $possible_names is an ref to an array of form element names.  As an example:
 8425: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8426: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8427: 
 8428: =cut
 8429: 
 8430: sub get_unprocessed_cgi {
 8431:   my ($query,$possible_names)= @_;
 8432:   # $Apache::lonxml::debug=1;
 8433:   foreach my $pair (split(/&/,$query)) {
 8434:     my ($name, $value) = split(/=/,$pair);
 8435:     $name = &unescape($name);
 8436:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8437:       $value =~ tr/+/ /;
 8438:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8439:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8440:     }
 8441:   }
 8442: }
 8443: 
 8444: =pod
 8445: 
 8446: =item * &cacheheader() 
 8447: 
 8448: returns cache-controlling header code
 8449: 
 8450: =cut
 8451: 
 8452: sub cacheheader {
 8453:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8454:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8455:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8456:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8457:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8458:     return $output;
 8459: }
 8460: 
 8461: =pod
 8462: 
 8463: =item * &no_cache($r) 
 8464: 
 8465: specifies header code to not have cache
 8466: 
 8467: =cut
 8468: 
 8469: sub no_cache {
 8470:     my ($r) = @_;
 8471:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8472: 	$env{'request.method'} ne 'GET') { return ''; }
 8473:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8474:     $r->no_cache(1);
 8475:     $r->header_out("Expires" => $date);
 8476:     $r->header_out("Pragma" => "no-cache");
 8477: }
 8478: 
 8479: sub content_type {
 8480:     my ($r,$type,$charset) = @_;
 8481:     if ($r) {
 8482: 	#  Note that printout.pl calls this with undef for $r.
 8483: 	&no_cache($r);
 8484:     }
 8485:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8486:     unless ($charset) {
 8487: 	$charset=&Apache::lonlocal::current_encoding;
 8488:     }
 8489:     if ($charset) { $type.='; charset='.$charset; }
 8490:     if ($r) {
 8491: 	$r->content_type($type);
 8492:     } else {
 8493: 	print("Content-type: $type\n\n");
 8494:     }
 8495: }
 8496: 
 8497: =pod
 8498: 
 8499: =item * &add_to_env($name,$value) 
 8500: 
 8501: adds $name to the %env hash with value
 8502: $value, if $name already exists, the entry is converted to an array
 8503: reference and $value is added to the array.
 8504: 
 8505: =cut
 8506: 
 8507: sub add_to_env {
 8508:   my ($name,$value)=@_;
 8509:   if (defined($env{$name})) {
 8510:     if (ref($env{$name})) {
 8511:       #already have multiple values
 8512:       push(@{ $env{$name} },$value);
 8513:     } else {
 8514:       #first time seeing multiple values, convert hash entry to an arrayref
 8515:       my $first=$env{$name};
 8516:       undef($env{$name});
 8517:       push(@{ $env{$name} },$first,$value);
 8518:     }
 8519:   } else {
 8520:     $env{$name}=$value;
 8521:   }
 8522: }
 8523: 
 8524: =pod
 8525: 
 8526: =item * &get_env_multiple($name) 
 8527: 
 8528: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8529: values may be defined and end up as an array ref.
 8530: 
 8531: returns an array of values
 8532: 
 8533: =cut
 8534: 
 8535: sub get_env_multiple {
 8536:     my ($name) = @_;
 8537:     my @values;
 8538:     if (defined($env{$name})) {
 8539:         # exists is it an array
 8540:         if (ref($env{$name})) {
 8541:             @values=@{ $env{$name} };
 8542:         } else {
 8543:             $values[0]=$env{$name};
 8544:         }
 8545:     }
 8546:     return(@values);
 8547: }
 8548: 
 8549: sub ask_for_embedded_content {
 8550:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8551:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
 8552:     my $num = 0;
 8553:     my $numremref = 0;
 8554:     my $numinvalid = 0;
 8555:     my $numpathchg = 0;
 8556:     my $numexisting = 0;
 8557:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
 8558:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8559:         my $current_path='/';
 8560:         if ($env{'form.currentpath'}) {
 8561:             $current_path = $env{'form.currentpath'};
 8562:         }
 8563:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 8564:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8565:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 8566:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 8567:         } else {
 8568:             $udom = $env{'user.domain'};
 8569:             $uname = $env{'user.name'};
 8570:             $url = '/userfiles/portfolio';
 8571:         }
 8572:         $toplevel = $url.'/';
 8573:         $url .= $current_path;
 8574:         $getpropath = 1;
 8575:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8576:              ($actionurl eq '/adm/imsimport')) {
 8577:         ($uname,my $rest) = ($args->{'current_path'} =~ m{/priv/($match_username)/?(.*)$});
 8578:         $url = '/home/'.$uname.'/public_html/';
 8579:         $toplevel = $url;
 8580:         if ($rest ne '') {
 8581:             $url .= $rest;
 8582:         }
 8583:     } elsif ($actionurl eq '/adm/coursedocs') {
 8584:         if (ref($args) eq 'HASH') {
 8585:            $url = $args->{'docs_url'};
 8586:            $toplevel = $url;
 8587:         }
 8588:     }
 8589:     my $now = time();
 8590:     foreach my $embed_file (keys(%{$allfiles})) {
 8591:         my $absolutepath;
 8592:         if ($embed_file =~ m{^\w+://}) {
 8593:             $newfiles{$embed_file} = 1;
 8594:             $mapping{$embed_file} = $embed_file;
 8595:         } else {
 8596:             if ($embed_file =~ m{^/}) {
 8597:                 $absolutepath = $embed_file;
 8598:                 $embed_file =~ s{^(/+)}{};
 8599:             }
 8600:             if ($embed_file =~ m{/}) {
 8601:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 8602:                 $path = &check_for_traversal($path,$url,$toplevel);
 8603:                 my $item = $fname;
 8604:                 if ($path ne '') {
 8605:                     $item = $path.'/'.$fname;
 8606:                     $subdependencies{$path}{$fname} = 1;
 8607:                 } else {
 8608:                     $dependencies{$item} = 1;
 8609:                 }
 8610:                 if ($absolutepath) {
 8611:                     $mapping{$item} = $absolutepath;
 8612:                 } else {
 8613:                     $mapping{$item} = $embed_file;
 8614:                 }
 8615:             } else {
 8616:                 $dependencies{$embed_file} = 1;
 8617:                 if ($absolutepath) {
 8618:                     $mapping{$embed_file} = $absolutepath;
 8619:                 } else {
 8620:                     $mapping{$embed_file} = $embed_file;
 8621:                 }
 8622:             }
 8623:         }
 8624:     }
 8625:     foreach my $path (keys(%subdependencies)) {
 8626:         my %currsubfile;
 8627:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8628:             my @subdir_list = &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 8629:             foreach my $line (@subdir_list) {
 8630:                 my ($file_name,$rest) = split(/\&/,$line,2);
 8631:                 $currsubfile{$file_name} = 1;
 8632:             }
 8633:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8634:             if (opendir(my $dir,$url.'/'.$path)) {
 8635:                 my @subdir_list = grep(!/^\./,readdir($dir));
 8636:                 map {$currsubfile{$_} = 1;} @subdir_list;
 8637:             }
 8638:         }
 8639:         foreach my $file (keys(%{$subdependencies{$path}})) {
 8640:             if ($currsubfile{$file}) {
 8641:                 my $item = $path.'/'.$file;
 8642:                 unless ($mapping{$item} eq $item) {
 8643:                     $pathchanges{$item} = 1;
 8644:                 }
 8645:                 $existing{$item} = 1;
 8646:                 $numexisting ++;
 8647:             } else {
 8648:                 $newfiles{$path.'/'.$file} = 1;
 8649:             }
 8650:         }
 8651:     }
 8652:     my %currfile;
 8653:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8654:         my @dir_list = &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 8655:         foreach my $line (@dir_list) {
 8656:             my ($file_name,$rest) = split(/\&/,$line,2);
 8657:             $currfile{$file_name} = 1;
 8658:         }
 8659:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8660:         if (opendir(my $dir,$url)) {
 8661:             my @dir_list = grep(!/^\./,readdir($dir));
 8662:             map {$currfile{$_} = 1;} @dir_list;
 8663:         }
 8664:     }
 8665:     foreach my $file (keys(%dependencies)) {
 8666:         if ($currfile{$file}) {
 8667:             unless ($mapping{$file} eq $file) {
 8668:                 $pathchanges{$file} = 1;
 8669:             }
 8670:             $existing{$file} = 1;
 8671:             $numexisting ++;
 8672:         } else {
 8673:             $newfiles{$file} = 1;
 8674:         }
 8675:     }
 8676:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 8677:         $upload_output .= &start_data_table_row().
 8678:                           '<td><span class="LC_filename">'.$embed_file.'</span>';
 8679:         unless ($mapping{$embed_file} eq $embed_file) {
 8680:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 8681:         }
 8682:         $upload_output .= '</td><td>';
 8683:         if ($args->{'ignore_remote_references'}
 8684:             && $embed_file =~ m{^\w+://}) {
 8685:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8686:             $numremref++;
 8687:         } elsif ($args->{'error_on_invalid_names'}
 8688:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8689: 
 8690:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 8691:             $numinvalid++;
 8692:         } else {
 8693:             $upload_output .= &embedded_file_element('upload_embedded',$num,
 8694:                                                      $embed_file,\%mapping,
 8695:                                                      $allfiles,$codebase);
 8696:             $num++;
 8697:         }
 8698:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 8699:     }
 8700:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 8701:         $upload_output .= &start_data_table_row().
 8702:                           '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
 8703:                           '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 8704:                           &Apache::loncommon::end_data_table_row()."\n";
 8705:     }
 8706:     if ($upload_output) {
 8707:         $upload_output = &start_data_table().
 8708:                          $upload_output.
 8709:                          &end_data_table()."\n";
 8710:     }
 8711:     my $applies = 0;
 8712:     if ($numremref) {
 8713:         $applies ++;
 8714:     }
 8715:     if ($numinvalid) {
 8716:         $applies ++;
 8717:     }
 8718:     if ($numexisting) {
 8719:         $applies ++;
 8720:     }
 8721:     if ($num) {
 8722:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 8723:                   ' method="post" enctype="multipart/form-data">'."\n".
 8724:                   $state.
 8725:                   '<h3>'.&mt('Upload embedded files').
 8726:                   ':</h3>'.$upload_output.'<br />'."\n".
 8727:                   '<input type ="hidden" name="number_embedded_items" value="'.
 8728:                   $num.'" />'."\n";
 8729:         if ($actionurl eq '') {
 8730:             $output .=  '<input type="hidden" name="phase" value="three" />';
 8731:         }
 8732:     } elsif ($applies) {
 8733:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 8734:         if ($applies > 1) {
 8735:             $output .=
 8736:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 8737:             if ($numremref) {
 8738:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 8739:             }
 8740:             if ($numinvalid) {
 8741:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 8742:             }
 8743:             if ($numexisting) {
 8744:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 8745:             }
 8746:             $output .= '</ul><br />';
 8747:         } elsif ($numremref) {
 8748:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 8749:         } elsif ($numinvalid) {
 8750:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 8751:         } elsif ($numexisting) {
 8752:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 8753:         }
 8754:         $output .= $upload_output.'<br />';
 8755:     }
 8756:     my ($pathchange_output,$chgcount);
 8757:     $chgcount = $num;
 8758:     if (keys(%pathchanges) > 0) {
 8759:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 8760:             if ($num) {
 8761:                 $output .= &embedded_file_element('pathchange',$chgcount,
 8762:                                                   $embed_file,\%mapping,
 8763:                                                   $allfiles,$codebase);
 8764:             } else {
 8765:                 $pathchange_output .=
 8766:                     &start_data_table_row().
 8767:                     '<td><input type ="checkbox" name="namechange" value="'.
 8768:                     $chgcount.'" checked="checked" /></td>'.
 8769:                     '<td>'.$mapping{$embed_file}.'</td>'.
 8770:                     '<td>'.$embed_file.
 8771:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 8772:                                            \%mapping,$allfiles,$codebase).
 8773:                     '</td>'.&end_data_table_row();
 8774:             }
 8775:             $numpathchg ++;
 8776:             $chgcount ++;
 8777:         }
 8778:     }
 8779:     if ($num) {
 8780:         if ($numpathchg) {
 8781:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 8782:                        $numpathchg.'" />'."\n";
 8783:         }
 8784:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8785:             ($actionurl eq '/adm/imsimport')) {
 8786:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 8787:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 8788:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 8789:         }
 8790:         $output .=  '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
 8791:                     &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
 8792:     } elsif ($numpathchg) {
 8793:         my %pathchange = ();
 8794:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 8795:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8796:             $output .= '<p>'.&mt('or').'</p>';
 8797:         }
 8798:     }
 8799:     return ($output,$num,$numpathchg);
 8800: }
 8801: 
 8802: sub embedded_file_element {
 8803:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
 8804:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 8805:                    (ref($codebase) eq 'HASH'));
 8806:     my $output;
 8807:     if ($context eq 'upload_embedded') {
 8808:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 8809:     }
 8810:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 8811:                &escape($embed_file).'" />';
 8812:     unless (($context eq 'upload_embedded') &&
 8813:             ($mapping->{$embed_file} eq $embed_file)) {
 8814:         $output .='
 8815:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 8816:     }
 8817:     my $attrib;
 8818:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 8819:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 8820:     }
 8821:     $output .=
 8822:         "\n\t\t".
 8823:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8824:         $attrib.'" />';
 8825:     if (exists($codebase->{$mapping->{$embed_file}})) {
 8826:         $output .=
 8827:             "\n\t\t".
 8828:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 8829:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 8830:     }
 8831:     return $output;
 8832: }
 8833: 
 8834: sub upload_embedded {
 8835:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8836:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 8837:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 8838:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8839:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8840:         my $orig_uploaded_filename =
 8841:             $env{'form.embedded_item_'.$i.'.filename'};
 8842:         foreach my $type ('orig','ref','attrib','codebase') {
 8843:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 8844:                 $env{'form.embedded_'.$type.'_'.$i} =
 8845:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 8846:             }
 8847:         }
 8848:         my ($path,$fname) =
 8849:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8850:         # no path, whole string is fname
 8851:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8852:         $fname = &Apache::lonnet::clean_filename($fname);
 8853:         # See if there is anything left
 8854:         next if ($fname eq '');
 8855: 
 8856:         # Check if file already exists as a file or directory.
 8857:         my ($state,$msg);
 8858:         if ($context eq 'portfolio') {
 8859:             my $port_path = $dirpath;
 8860:             if ($group ne '') {
 8861:                 $port_path = "groups/$group/$port_path";
 8862:             }
 8863:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 8864:                                               $fname,$group,'embedded_item_'.$i,
 8865:                                               $dir_root,$port_path,$disk_quota,
 8866:                                               $current_disk_usage,$uname,$udom);
 8867:             if ($state eq 'will_exceed_quota'
 8868:                 || $state eq 'file_locked') {
 8869:                 $output .= $msg;
 8870:                 next;
 8871:             }
 8872:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8873:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8874:             if ($state eq 'exists') {
 8875:                 $output .= $msg;
 8876:                 next;
 8877:             }
 8878:         }
 8879:         # Check if extension is valid
 8880:         if (($fname =~ /\.(\w+)$/) &&
 8881:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8882:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 8883:             next;
 8884:         } elsif (($fname =~ /\.(\w+)$/) &&
 8885:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8886:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 8887:             next;
 8888:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8889:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 8890:             next;
 8891:         }
 8892: 
 8893:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8894:         if ($context eq 'portfolio') {
 8895:             my $result;
 8896:             if ($state eq 'existingfile') {
 8897:                 $result=
 8898:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
 8899:                                                     $dirpath.$env{'form.currentpath'}.$path);
 8900:             } else {
 8901:                 $result=
 8902:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8903:                                                     $dirpath.
 8904:                                                     $env{'form.currentpath'}.$path);
 8905:                 if ($result !~ m|^/uploaded/|) {
 8906:                     $output .= '<span class="LC_error">'
 8907:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8908:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8909:                                .'</span><br />';
 8910:                     next;
 8911:                 } else {
 8912:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8913:                                $path.$fname.'</span>').'<br />'; 
 8914:                 }
 8915:             }
 8916:         } elsif ($context eq 'coursedoc') {
 8917:             my $result =
 8918:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
 8919:                                                 $dirpath.'/'.$path);
 8920:             if ($result !~ m|^/uploaded/|) {
 8921:                 $output .= '<span class="LC_error">'
 8922:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8923:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8924:                            .'</span><br />';
 8925:                     next;
 8926:             } else {
 8927:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8928:                            $path.$fname.'</span>').'<br />';
 8929:             }
 8930:         } else {
 8931: # Save the file
 8932:             my $target = $env{'form.embedded_item_'.$i};
 8933:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8934:             my $dest = $fullpath.$fname;
 8935:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8936:             my @parts=split(/\//,$fullpath);
 8937:             my $count;
 8938:             my $filepath = $dir_root;
 8939:             for ($count=4;$count<=$#parts;$count++) {
 8940:                 $filepath .= "/$parts[$count]";
 8941:                 if ((-e $filepath)!=1) {
 8942:                     mkdir($filepath,0770);
 8943:                 }
 8944:             }
 8945:             my $fh;
 8946:             if (!open($fh,'>'.$dest)) {
 8947:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8948:                 $output .= '<span class="LC_error">'.
 8949:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8950:                            '</span><br />';
 8951:             } else {
 8952:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8953:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8954:                     $output .= '<span class="LC_error">'.
 8955:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8956:                               '</span><br />';
 8957:                 } else {
 8958:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8959:                                $url.'</span>').'<br />';
 8960:                     unless ($context eq 'testbank') {
 8961:                         $footer .= &mt('View embedded file: [_1]',
 8962:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
 8963:                     }
 8964:                 }
 8965:                 close($fh);
 8966:             }
 8967:         }
 8968:         if ($env{'form.embedded_ref_'.$i}) {
 8969:             $pathchange{$i} = 1;
 8970:         }
 8971:     }
 8972:     if ($output) {
 8973:         $output = '<p>'.$output.'</p>';
 8974:     }
 8975:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
 8976:     $returnflag = 'ok';
 8977:     if (keys(%pathchange) > 0) {
 8978:         if ($context eq 'portfolio') {
 8979:             $output .= '<p>'.&mt('or').'</p>';
 8980:         } elsif ($context eq 'testbank') {
 8981:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
 8982:             $returnflag = 'modify_orightml';
 8983:         }
 8984:     }
 8985:     return ($output.$footer,$returnflag);
 8986: }
 8987: 
 8988: sub modify_html_form {
 8989:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
 8990:     my $end = 0;
 8991:     my $modifyform;
 8992:     if ($context eq 'upload_embedded') {
 8993:         return unless (ref($pathchange) eq 'HASH');
 8994:         if ($env{'form.number_embedded_items'}) {
 8995:             $end += $env{'form.number_embedded_items'};
 8996:         }
 8997:         if ($env{'form.number_pathchange_items'}) {
 8998:             $end += $env{'form.number_pathchange_items'};
 8999:         }
 9000:         if ($end) {
 9001:             for (my $i=0; $i<$end; $i++) {
 9002:                 if ($i < $env{'form.number_embedded_items'}) {
 9003:                     next unless($pathchange->{$i});
 9004:                 }
 9005:                 $modifyform .=
 9006:                     &start_data_table_row().
 9007:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
 9008:                     'checked="checked" /></td>'.
 9009:                     '<td>'.$env{'form.embedded_ref_'.$i}.
 9010:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
 9011:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
 9012:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
 9013:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
 9014:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
 9015:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
 9016:                     '<td>'.$env{'form.embedded_orig_'.$i}.
 9017:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
 9018:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
 9019:                     &end_data_table_row();
 9020:             }
 9021:         }
 9022:     } else {
 9023:         $modifyform = $pathchgtable;
 9024:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9025:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
 9026:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9027:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
 9028:         }
 9029:     }
 9030:     if ($modifyform) {
 9031:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
 9032:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
 9033:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
 9034:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
 9035:                '</ol></p>'."\n".'<p>'.
 9036:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
 9037:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
 9038:                &start_data_table()."\n".
 9039:                &start_data_table_header_row().
 9040:                '<th>'.&mt('Change?').'</th>'.
 9041:                '<th>'.&mt('Current reference').'</th>'.
 9042:                '<th>'.&mt('Required reference').'</th>'.
 9043:                &end_data_table_header_row()."\n".
 9044:                $modifyform.
 9045:                &end_data_table().'<br />'."\n".$hiddenstate.
 9046:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
 9047:                '</form>'."\n";
 9048:     }
 9049:     return;
 9050: }
 9051: 
 9052: sub modify_html_refs {
 9053:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
 9054:     my $container;
 9055:     if ($context eq 'portfolio') {
 9056:         $container = $env{'form.container'};
 9057:     } elsif ($context eq 'coursedoc') {
 9058:         $container = $env{'form.primaryurl'};
 9059:     } else {
 9060:         $container = $env{'form.filename'};
 9061:         $container =~ s{^/priv/(\Q$uname\E)/(.*)}{/home/$1/public_html/$2};
 9062:     }
 9063:     my (%allfiles,%codebase,$output,$content);
 9064:     my @changes = &get_env_multiple('form.namechange');
 9065:     return unless (@changes > 0);
 9066:     if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
 9067:         return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
 9068:         $content = &Apache::lonnet::getfile($container);
 9069:         return if ($content eq '-1');
 9070:     } else {
 9071:         return unless ($container =~ /^\Q$dir_root\E/);
 9072:         if (open(my $fh,"<$container")) {
 9073:             $content = join('', <$fh>);
 9074:             close($fh);
 9075:         } else {
 9076:             return;
 9077:         }
 9078:     }
 9079:     my ($count,$codebasecount) = (0,0);
 9080:     my $mm = new File::MMagic;
 9081:     my $mime_type = $mm->checktype_contents($content);
 9082:     if ($mime_type eq 'text/html') {
 9083:         my $parse_result =
 9084:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
 9085:                                                     \%codebase,\$content);
 9086:         if ($parse_result eq 'ok') {
 9087:             foreach my $i (@changes) {
 9088:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
 9089:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
 9090:                 if ($allfiles{$ref}) {
 9091:                     my $newname =  $orig;
 9092:                     my ($attrib_regexp,$codebase);
 9093:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
 9094:                     if ($attrib_regexp =~ /:/) {
 9095:                         $attrib_regexp =~ s/\:/|/g;
 9096:                     }
 9097:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
 9098:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
 9099:                         $count += $numchg;
 9100:                     }
 9101:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
 9102:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
 9103:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
 9104:                         $codebasecount ++;
 9105:                     }
 9106:                 }
 9107:             }
 9108:             if ($count || $codebasecount) {
 9109:                 my $saveresult;
 9110:                 if ($context eq 'portfolio' || $context eq 'coursedoc') {
 9111:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
 9112:                     if ($url eq $container) {
 9113:                         my ($fname) = ($container =~ m{/([^/]+)$});
 9114:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9115:                                             $count,'<span class="LC_filename">'.
 9116:                                             $fname.'</span>').'</p>';
 9117:                     } else {
 9118:                          $output = '<p class="LC_error">'.
 9119:                                    &mt('Error: update failed for: [_1].',
 9120:                                    '<span class="LC_filename">'.
 9121:                                    $container.'</span>').'</p>';
 9122:                     }
 9123:                 } else {
 9124:                     if (open(my $fh,">$container")) {
 9125:                         print $fh $content;
 9126:                         close($fh);
 9127:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9128:                                   $count,'<span class="LC_filename">'.
 9129:                                   $container.'</span>').'</p>';
 9130:                     } else {
 9131:                          $output = '<p class="LC_error">'.
 9132:                                    &mt('Error: could not update [_1].',
 9133:                                    '<span class="LC_filename">'.
 9134:                                    $container.'</span>').'</p>';
 9135:                     }
 9136:                 }
 9137:             }
 9138:         } else {
 9139:             &logthis('Failed to parse '.$container.
 9140:                      ' to modify references: '.$parse_result);
 9141:         }
 9142:     }
 9143:     return $output;
 9144: }
 9145: 
 9146: sub check_for_existing {
 9147:     my ($path,$fname,$element) = @_;
 9148:     my ($state,$msg);
 9149:     if (-d $path.'/'.$fname) {
 9150:         $state = 'exists';
 9151:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 9152:     } elsif (-e $path.'/'.$fname) {
 9153:         $state = 'exists';
 9154:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 9155:     }
 9156:     if ($state eq 'exists') {
 9157:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 9158:     }
 9159:     return ($state,$msg);
 9160: }
 9161: 
 9162: sub check_for_upload {
 9163:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 9164:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 9165:     my $filesize = length($env{'form.'.$element});
 9166:     if (!$filesize) {
 9167:         my $msg = '<span class="LC_error">'.
 9168:                   &mt('Unable to upload [_1]. (size = [_2] bytes)',
 9169:                       '<span class="LC_filename">'.$fname.'</span>',
 9170:                       $filesize).'<br />'.
 9171:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
 9172:                   '</span>';
 9173:         return ('zero_bytes',$msg);
 9174:     }
 9175:     $filesize =  $filesize/1000; #express in k (1024?)
 9176:     my $getpropath = 1;
 9177:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 9178:                                             $getpropath);
 9179:     my $found_file = 0;
 9180:     my $locked_file = 0;
 9181:     my @lockers;
 9182:     my $navmap;
 9183:     if ($env{'request.course.id'}) {
 9184:         $navmap = Apache::lonnavmaps::navmap->new();
 9185:     }
 9186:     foreach my $line (@dir_list) {
 9187:         my ($file_name,$rest)=split(/\&/,$line,2);
 9188:         if ($file_name eq $fname){
 9189:             $file_name = $path.$file_name;
 9190:             if ($group ne '') {
 9191:                 $file_name = $group.$file_name;
 9192:             }
 9193:             $found_file = 1;
 9194:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
 9195:                 foreach my $lock (@lockers) {
 9196:                     if (ref($lock) eq 'ARRAY') {
 9197:                         my ($symb,$crsid) = @{$lock};
 9198:                         if ($crsid eq $env{'request.course.id'}) {
 9199:                             if (ref($navmap)) {
 9200:                                 my $res = $navmap->getBySymb($symb);
 9201:                                 foreach my $part (@{$res->parts()}) {
 9202:                                     my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
 9203:                                     unless (($slot_status == $res->RESERVED) ||
 9204:                                             ($slot_status == $res->RESERVED_LOCATION)) {
 9205:                                         $locked_file = 1;
 9206:                                     }
 9207:                                 }
 9208:                             } else {
 9209:                                 $locked_file = 1;
 9210:                             }
 9211:                         } else {
 9212:                             $locked_file = 1;
 9213:                         }
 9214:                     }
 9215:                 }
 9216:             } else {
 9217:                 my @info = split(/\&/,$rest);
 9218:                 my $currsize = $info[6]/1000;
 9219:                 if ($currsize < $filesize) {
 9220:                     my $extra = $filesize - $currsize;
 9221:                     if (($current_disk_usage + $extra) > $disk_quota) {
 9222:                         my $msg = '<span class="LC_error">'.
 9223:                                   &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
 9224:                                       '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
 9225:                                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9226:                                                $disk_quota,$current_disk_usage);
 9227:                         return ('will_exceed_quota',$msg);
 9228:                     }
 9229:                 }
 9230:             }
 9231:         }
 9232:     }
 9233:     if (($current_disk_usage + $filesize) > $disk_quota){
 9234:         my $msg = '<span class="LC_error">'.
 9235:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 9236:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 9237:         return ('will_exceed_quota',$msg);
 9238:     } elsif ($found_file) {
 9239:         if ($locked_file) {
 9240:             my $msg = '<span class="LC_error">';
 9241:             $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>');
 9242:             $msg .= '</span><br />';
 9243:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 9244:             return ('file_locked',$msg);
 9245:         } else {
 9246:             my $msg = '<span class="LC_error">';
 9247:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 9248:             $msg .= '</span>';
 9249:             return ('existingfile',$msg);
 9250:         }
 9251:     }
 9252: }
 9253: 
 9254: sub check_for_traversal {
 9255:     my ($path,$url,$toplevel) = @_;
 9256:     my @parts=split(/\//,$path);
 9257:     my $cleanpath;
 9258:     my $fullpath = $url;
 9259:     for (my $i=0;$i<@parts;$i++) {
 9260:         next if ($parts[$i] eq '.');
 9261:         if ($parts[$i] eq '..') {
 9262:             $fullpath =~ s{([^/]+/)$}{};
 9263:         } else {
 9264:             $fullpath .= $parts[$i].'/';
 9265:         }
 9266:     }
 9267:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
 9268:         $cleanpath = $1;
 9269:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
 9270:         my $curr_toprel = $1;
 9271:         my @parts = split(/\//,$curr_toprel);
 9272:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
 9273:         my @urlparts = split(/\//,$url_toprel);
 9274:         my $doubledots;
 9275:         my $startdiff = -1;
 9276:         for (my $i=0; $i<@urlparts; $i++) {
 9277:             if ($startdiff == -1) {
 9278:                 unless ($urlparts[$i] eq $parts[$i]) {
 9279:                     $startdiff = $i;
 9280:                     $doubledots .= '../';
 9281:                 }
 9282:             } else {
 9283:                 $doubledots .= '../';
 9284:             }
 9285:         }
 9286:         if ($startdiff > -1) {
 9287:             $cleanpath = $doubledots;
 9288:             for (my $i=$startdiff; $i<@parts; $i++) {
 9289:                 $cleanpath .= $parts[$i].'/';
 9290:             }
 9291:         }
 9292:     }
 9293:     $cleanpath =~ s{(/)$}{};
 9294:     return $cleanpath;
 9295: }
 9296: 
 9297: =pod
 9298: 
 9299: =back
 9300: 
 9301: =head1 CSV Upload/Handling functions
 9302: 
 9303: =over 4
 9304: 
 9305: =item * &upfile_store($r)
 9306: 
 9307: Store uploaded file, $r should be the HTTP Request object,
 9308: needs $env{'form.upfile'}
 9309: returns $datatoken to be put into hidden field
 9310: 
 9311: =cut
 9312: 
 9313: sub upfile_store {
 9314:     my $r=shift;
 9315:     $env{'form.upfile'}=~s/\r/\n/gs;
 9316:     $env{'form.upfile'}=~s/\f/\n/gs;
 9317:     $env{'form.upfile'}=~s/\n+/\n/gs;
 9318:     $env{'form.upfile'}=~s/\n+$//gs;
 9319: 
 9320:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 9321: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 9322:     {
 9323:         my $datafile = $r->dir_config('lonDaemons').
 9324:                            '/tmp/'.$datatoken.'.tmp';
 9325:         if ( open(my $fh,">$datafile") ) {
 9326:             print $fh $env{'form.upfile'};
 9327:             close($fh);
 9328:         }
 9329:     }
 9330:     return $datatoken;
 9331: }
 9332: 
 9333: =pod
 9334: 
 9335: =item * &load_tmp_file($r)
 9336: 
 9337: Load uploaded file from tmp, $r should be the HTTP Request object,
 9338: needs $env{'form.datatoken'},
 9339: sets $env{'form.upfile'} to the contents of the file
 9340: 
 9341: =cut
 9342: 
 9343: sub load_tmp_file {
 9344:     my $r=shift;
 9345:     my @studentdata=();
 9346:     {
 9347:         my $studentfile = $r->dir_config('lonDaemons').
 9348:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 9349:         if ( open(my $fh,"<$studentfile") ) {
 9350:             @studentdata=<$fh>;
 9351:             close($fh);
 9352:         }
 9353:     }
 9354:     $env{'form.upfile'}=join('',@studentdata);
 9355: }
 9356: 
 9357: =pod
 9358: 
 9359: =item * &upfile_record_sep()
 9360: 
 9361: Separate uploaded file into records
 9362: returns array of records,
 9363: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 9364: 
 9365: =cut
 9366: 
 9367: sub upfile_record_sep {
 9368:     if ($env{'form.upfiletype'} eq 'xml') {
 9369:     } else {
 9370: 	my @records;
 9371: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 9372: 	    if ($line=~/^\s*$/) { next; }
 9373: 	    push(@records,$line);
 9374: 	}
 9375: 	return @records;
 9376:     }
 9377: }
 9378: 
 9379: =pod
 9380: 
 9381: =item * &record_sep($record)
 9382: 
 9383: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 9384: 
 9385: =cut
 9386: 
 9387: sub takeleft {
 9388:     my $index=shift;
 9389:     return substr('0000'.$index,-4,4);
 9390: }
 9391: 
 9392: sub record_sep {
 9393:     my $record=shift;
 9394:     my %components=();
 9395:     if ($env{'form.upfiletype'} eq 'xml') {
 9396:     } elsif ($env{'form.upfiletype'} eq 'space') {
 9397:         my $i=0;
 9398:         foreach my $field (split(/\s+/,$record)) {
 9399:             $field=~s/^(\"|\')//;
 9400:             $field=~s/(\"|\')$//;
 9401:             $components{&takeleft($i)}=$field;
 9402:             $i++;
 9403:         }
 9404:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 9405:         my $i=0;
 9406:         foreach my $field (split(/\t/,$record)) {
 9407:             $field=~s/^(\"|\')//;
 9408:             $field=~s/(\"|\')$//;
 9409:             $components{&takeleft($i)}=$field;
 9410:             $i++;
 9411:         }
 9412:     } else {
 9413:         my $separator=',';
 9414:         if ($env{'form.upfiletype'} eq 'semisv') {
 9415:             $separator=';';
 9416:         }
 9417:         my $i=0;
 9418: # the character we are looking for to indicate the end of a quote or a record 
 9419:         my $looking_for=$separator;
 9420: # do not add the characters to the fields
 9421:         my $ignore=0;
 9422: # we just encountered a separator (or the beginning of the record)
 9423:         my $just_found_separator=1;
 9424: # store the field we are working on here
 9425:         my $field='';
 9426: # work our way through all characters in record
 9427:         foreach my $character ($record=~/(.)/g) {
 9428:             if ($character eq $looking_for) {
 9429:                if ($character ne $separator) {
 9430: # Found the end of a quote, again looking for separator
 9431:                   $looking_for=$separator;
 9432:                   $ignore=1;
 9433:                } else {
 9434: # Found a separator, store away what we got
 9435:                   $components{&takeleft($i)}=$field;
 9436: 	          $i++;
 9437:                   $just_found_separator=1;
 9438:                   $ignore=0;
 9439:                   $field='';
 9440:                }
 9441:                next;
 9442:             }
 9443: # single or double quotation marks after a separator indicate beginning of a quote
 9444: # we are now looking for the end of the quote and need to ignore separators
 9445:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 9446:                $looking_for=$character;
 9447:                next;
 9448:             }
 9449: # ignore would be true after we reached the end of a quote
 9450:             if ($ignore) { next; }
 9451:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 9452:             $field.=$character;
 9453:             $just_found_separator=0; 
 9454:         }
 9455: # catch the very last entry, since we never encountered the separator
 9456:         $components{&takeleft($i)}=$field;
 9457:     }
 9458:     return %components;
 9459: }
 9460: 
 9461: ######################################################
 9462: ######################################################
 9463: 
 9464: =pod
 9465: 
 9466: =item * &upfile_select_html()
 9467: 
 9468: Return HTML code to select a file from the users machine and specify 
 9469: the file type.
 9470: 
 9471: =cut
 9472: 
 9473: ######################################################
 9474: ######################################################
 9475: sub upfile_select_html {
 9476:     my %Types = (
 9477:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 9478:                  semisv => &mt('Semicolon separated values'),
 9479:                  space => &mt('Space separated'),
 9480:                  tab   => &mt('Tabulator separated'),
 9481: #                 xml   => &mt('HTML/XML'),
 9482:                  );
 9483:     my $Str = '<input type="file" name="upfile" size="50" />'.
 9484:         '<br />'.&mt('Type').': <select name="upfiletype">';
 9485:     foreach my $type (sort(keys(%Types))) {
 9486:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 9487:     }
 9488:     $Str .= "</select>\n";
 9489:     return $Str;
 9490: }
 9491: 
 9492: sub get_samples {
 9493:     my ($records,$toget) = @_;
 9494:     my @samples=({});
 9495:     my $got=0;
 9496:     foreach my $rec (@$records) {
 9497: 	my %temp = &record_sep($rec);
 9498: 	if (! grep(/\S/, values(%temp))) { next; }
 9499: 	if (%temp) {
 9500: 	    $samples[$got]=\%temp;
 9501: 	    $got++;
 9502: 	    if ($got == $toget) { last; }
 9503: 	}
 9504:     }
 9505:     return \@samples;
 9506: }
 9507: 
 9508: ######################################################
 9509: ######################################################
 9510: 
 9511: =pod
 9512: 
 9513: =item * &csv_print_samples($r,$records)
 9514: 
 9515: Prints a table of sample values from each column uploaded $r is an
 9516: Apache Request ref, $records is an arrayref from
 9517: &Apache::loncommon::upfile_record_sep
 9518: 
 9519: =cut
 9520: 
 9521: ######################################################
 9522: ######################################################
 9523: sub csv_print_samples {
 9524:     my ($r,$records) = @_;
 9525:     my $samples = &get_samples($records,5);
 9526: 
 9527:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 9528:               &start_data_table_header_row());
 9529:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 9530:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 9531:     $r->print(&end_data_table_header_row());
 9532:     foreach my $hash (@$samples) {
 9533: 	$r->print(&start_data_table_row());
 9534: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9535: 	    $r->print('<td>');
 9536: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 9537: 	    $r->print('</td>');
 9538: 	}
 9539: 	$r->print(&end_data_table_row());
 9540:     }
 9541:     $r->print(&end_data_table().'<br />'."\n");
 9542: }
 9543: 
 9544: ######################################################
 9545: ######################################################
 9546: 
 9547: =pod
 9548: 
 9549: =item * &csv_print_select_table($r,$records,$d)
 9550: 
 9551: Prints a table to create associations between values and table columns.
 9552: 
 9553: $r is an Apache Request ref,
 9554: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9555: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 9556: 
 9557: =cut
 9558: 
 9559: ######################################################
 9560: ######################################################
 9561: sub csv_print_select_table {
 9562:     my ($r,$records,$d) = @_;
 9563:     my $i=0;
 9564:     my $samples = &get_samples($records,1);
 9565:     $r->print(&mt('Associate columns with student attributes.')."\n".
 9566: 	      &start_data_table().&start_data_table_header_row().
 9567:               '<th>'.&mt('Attribute').'</th>'.
 9568:               '<th>'.&mt('Column').'</th>'.
 9569:               &end_data_table_header_row()."\n");
 9570:     foreach my $array_ref (@$d) {
 9571: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 9572: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 9573: 
 9574: 	$r->print('<td><select name="f'.$i.'"'.
 9575: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9576: 	$r->print('<option value="none"></option>');
 9577: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9578: 	    $r->print('<option value="'.$sample.'"'.
 9579:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 9580:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 9581: 	}
 9582: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 9583: 	$i++;
 9584:     }
 9585:     $r->print(&end_data_table());
 9586:     $i--;
 9587:     return $i;
 9588: }
 9589: 
 9590: ######################################################
 9591: ######################################################
 9592: 
 9593: =pod
 9594: 
 9595: =item * &csv_samples_select_table($r,$records,$d)
 9596: 
 9597: Prints a table of sample values from the upload and can make associate samples to internal names.
 9598: 
 9599: $r is an Apache Request ref,
 9600: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9601: $d is an array of 2 element arrays (internal name, displayed name)
 9602: 
 9603: =cut
 9604: 
 9605: ######################################################
 9606: ######################################################
 9607: sub csv_samples_select_table {
 9608:     my ($r,$records,$d) = @_;
 9609:     my $i=0;
 9610:     #
 9611:     my $max_samples = 5;
 9612:     my $samples = &get_samples($records,$max_samples);
 9613:     $r->print(&start_data_table().
 9614:               &start_data_table_header_row().'<th>'.
 9615:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 9616:               &end_data_table_header_row());
 9617: 
 9618:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 9619: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 9620: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9621: 	foreach my $option (@$d) {
 9622: 	    my ($value,$display,$defaultcol)=@{ $option };
 9623: 	    $r->print('<option value="'.$value.'"'.
 9624:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 9625:                       $display.'</option>');
 9626: 	}
 9627: 	$r->print('</select></td><td>');
 9628: 	foreach my $line (0..($max_samples-1)) {
 9629: 	    if (defined($samples->[$line]{$key})) { 
 9630: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 9631: 	    }
 9632: 	}
 9633: 	$r->print('</td>'.&end_data_table_row());
 9634: 	$i++;
 9635:     }
 9636:     $r->print(&end_data_table());
 9637:     $i--;
 9638:     return($i);
 9639: }
 9640: 
 9641: ######################################################
 9642: ######################################################
 9643: 
 9644: =pod
 9645: 
 9646: =item * &clean_excel_name($name)
 9647: 
 9648: Returns a replacement for $name which does not contain any illegal characters.
 9649: 
 9650: =cut
 9651: 
 9652: ######################################################
 9653: ######################################################
 9654: sub clean_excel_name {
 9655:     my ($name) = @_;
 9656:     $name =~ s/[:\*\?\/\\]//g;
 9657:     if (length($name) > 31) {
 9658:         $name = substr($name,0,31);
 9659:     }
 9660:     return $name;
 9661: }
 9662: 
 9663: =pod
 9664: 
 9665: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 9666: 
 9667: Returns either 1 or undef
 9668: 
 9669: 1 if the part is to be hidden, undef if it is to be shown
 9670: 
 9671: Arguments are:
 9672: 
 9673: $id the id of the part to be checked
 9674: $symb, optional the symb of the resource to check
 9675: $udom, optional the domain of the user to check for
 9676: $uname, optional the username of the user to check for
 9677: 
 9678: =cut
 9679: 
 9680: sub check_if_partid_hidden {
 9681:     my ($id,$symb,$udom,$uname) = @_;
 9682:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 9683: 					 $symb,$udom,$uname);
 9684:     my $truth=1;
 9685:     #if the string starts with !, then the list is the list to show not hide
 9686:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 9687:     my @hiddenlist=split(/,/,$hiddenparts);
 9688:     foreach my $checkid (@hiddenlist) {
 9689: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 9690:     }
 9691:     return !$truth;
 9692: }
 9693: 
 9694: 
 9695: ############################################################
 9696: ############################################################
 9697: 
 9698: =pod
 9699: 
 9700: =back 
 9701: 
 9702: =head1 cgi-bin script and graphing routines
 9703: 
 9704: =over 4
 9705: 
 9706: =item * &get_cgi_id()
 9707: 
 9708: Inputs: none
 9709: 
 9710: Returns an id which can be used to pass environment variables
 9711: to various cgi-bin scripts.  These environment variables will
 9712: be removed from the users environment after a given time by
 9713: the routine &Apache::lonnet::transfer_profile_to_env.
 9714: 
 9715: =cut
 9716: 
 9717: ############################################################
 9718: ############################################################
 9719: my $uniq=0;
 9720: sub get_cgi_id {
 9721:     $uniq=($uniq+1)%100000;
 9722:     return (time.'_'.$$.'_'.$uniq);
 9723: }
 9724: 
 9725: ############################################################
 9726: ############################################################
 9727: 
 9728: =pod
 9729: 
 9730: =item * &DrawBarGraph()
 9731: 
 9732: Facilitates the plotting of data in a (stacked) bar graph.
 9733: Puts plot definition data into the users environment in order for 
 9734: graph.png to plot it.  Returns an <img> tag for the plot.
 9735: The bars on the plot are labeled '1','2',...,'n'.
 9736: 
 9737: Inputs:
 9738: 
 9739: =over 4
 9740: 
 9741: =item $Title: string, the title of the plot
 9742: 
 9743: =item $xlabel: string, text describing the X-axis of the plot
 9744: 
 9745: =item $ylabel: string, text describing the Y-axis of the plot
 9746: 
 9747: =item $Max: scalar, the maximum Y value to use in the plot
 9748: If $Max is < any data point, the graph will not be rendered.
 9749: 
 9750: =item $colors: array ref holding the colors to be used for the data sets when
 9751: they are plotted.  If undefined, default values will be used.
 9752: 
 9753: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 9754: 
 9755: =item @Values: An array of array references.  Each array reference holds data
 9756: to be plotted in a stacked bar chart.
 9757: 
 9758: =item If the final element of @Values is a hash reference the key/value
 9759: pairs will be added to the graph definition.
 9760: 
 9761: =back
 9762: 
 9763: Returns:
 9764: 
 9765: An <img> tag which references graph.png and the appropriate identifying
 9766: information for the plot.
 9767: 
 9768: =cut
 9769: 
 9770: ############################################################
 9771: ############################################################
 9772: sub DrawBarGraph {
 9773:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9774:     #
 9775:     if (! defined($colors)) {
 9776:         $colors = ['#33ff00', 
 9777:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9778:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9779:                   ]; 
 9780:     }
 9781:     my $extra_settings = {};
 9782:     if (ref($Values[-1]) eq 'HASH') {
 9783:         $extra_settings = pop(@Values);
 9784:     }
 9785:     #
 9786:     my $identifier = &get_cgi_id();
 9787:     my $id = 'cgi.'.$identifier;        
 9788:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9789:         return '';
 9790:     }
 9791:     #
 9792:     my @Labels;
 9793:     if (defined($labels)) {
 9794:         @Labels = @$labels;
 9795:     } else {
 9796:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9797:             push (@Labels,$i+1);
 9798:         }
 9799:     }
 9800:     #
 9801:     my $NumBars = scalar(@{$Values[0]});
 9802:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9803:     my %ValuesHash;
 9804:     my $NumSets=1;
 9805:     foreach my $array (@Values) {
 9806:         next if (! ref($array));
 9807:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9808:             join(',',@$array);
 9809:     }
 9810:     #
 9811:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9812:     if ($NumBars < 3) {
 9813:         $width = 120+$NumBars*32;
 9814:         $xskip = 1;
 9815:         $bar_width = 30;
 9816:     } elsif ($NumBars < 5) {
 9817:         $width = 120+$NumBars*20;
 9818:         $xskip = 1;
 9819:         $bar_width = 20;
 9820:     } elsif ($NumBars < 10) {
 9821:         $width = 120+$NumBars*15;
 9822:         $xskip = 1;
 9823:         $bar_width = 15;
 9824:     } elsif ($NumBars <= 25) {
 9825:         $width = 120+$NumBars*11;
 9826:         $xskip = 5;
 9827:         $bar_width = 8;
 9828:     } elsif ($NumBars <= 50) {
 9829:         $width = 120+$NumBars*8;
 9830:         $xskip = 5;
 9831:         $bar_width = 4;
 9832:     } else {
 9833:         $width = 120+$NumBars*8;
 9834:         $xskip = 5;
 9835:         $bar_width = 4;
 9836:     }
 9837:     #
 9838:     $Max = 1 if ($Max < 1);
 9839:     if ( int($Max) < $Max ) {
 9840:         $Max++;
 9841:         $Max = int($Max);
 9842:     }
 9843:     $Title  = '' if (! defined($Title));
 9844:     $xlabel = '' if (! defined($xlabel));
 9845:     $ylabel = '' if (! defined($ylabel));
 9846:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9847:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9848:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9849:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9850:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9851:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9852:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9853:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9854:     $ValuesHash{$id.'.height'}   = $height;
 9855:     $ValuesHash{$id.'.width'}    = $width;
 9856:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9857:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 9858:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 9859:     #
 9860:     # Deal with other parameters
 9861:     while (my ($key,$value) = each(%$extra_settings)) {
 9862:         $ValuesHash{$id.'.'.$key} = $value;
 9863:     }
 9864:     #
 9865:     &Apache::lonnet::appenv(\%ValuesHash);
 9866:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9867: }
 9868: 
 9869: ############################################################
 9870: ############################################################
 9871: 
 9872: =pod
 9873: 
 9874: =item * &DrawXYGraph()
 9875: 
 9876: Facilitates the plotting of data in an XY graph.
 9877: Puts plot definition data into the users environment in order for 
 9878: graph.png to plot it.  Returns an <img> tag for the plot.
 9879: 
 9880: Inputs:
 9881: 
 9882: =over 4
 9883: 
 9884: =item $Title: string, the title of the plot
 9885: 
 9886: =item $xlabel: string, text describing the X-axis of the plot
 9887: 
 9888: =item $ylabel: string, text describing the Y-axis of the plot
 9889: 
 9890: =item $Max: scalar, the maximum Y value to use in the plot
 9891: If $Max is < any data point, the graph will not be rendered.
 9892: 
 9893: =item $colors: Array ref containing the hex color codes for the data to be 
 9894: plotted in.  If undefined, default values will be used.
 9895: 
 9896: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9897: 
 9898: =item $Ydata: Array ref containing Array refs.  
 9899: Each of the contained arrays will be plotted as a separate curve.
 9900: 
 9901: =item %Values: hash indicating or overriding any default values which are 
 9902: passed to graph.png.  
 9903: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9904: 
 9905: =back
 9906: 
 9907: Returns:
 9908: 
 9909: An <img> tag which references graph.png and the appropriate identifying
 9910: information for the plot.
 9911: 
 9912: =cut
 9913: 
 9914: ############################################################
 9915: ############################################################
 9916: sub DrawXYGraph {
 9917:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9918:     #
 9919:     # Create the identifier for the graph
 9920:     my $identifier = &get_cgi_id();
 9921:     my $id = 'cgi.'.$identifier;
 9922:     #
 9923:     $Title  = '' if (! defined($Title));
 9924:     $xlabel = '' if (! defined($xlabel));
 9925:     $ylabel = '' if (! defined($ylabel));
 9926:     my %ValuesHash = 
 9927:         (
 9928:          $id.'.title'  => &escape($Title),
 9929:          $id.'.xlabel' => &escape($xlabel),
 9930:          $id.'.ylabel' => &escape($ylabel),
 9931:          $id.'.y_max_value'=> $Max,
 9932:          $id.'.labels'     => join(',',@$Xlabels),
 9933:          $id.'.PlotType'   => 'XY',
 9934:          );
 9935:     #
 9936:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9937:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9938:     }
 9939:     #
 9940:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9941:         return '';
 9942:     }
 9943:     my $NumSets=1;
 9944:     foreach my $array (@{$Ydata}){
 9945:         next if (! ref($array));
 9946:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9947:     }
 9948:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9949:     #
 9950:     # Deal with other parameters
 9951:     while (my ($key,$value) = each(%Values)) {
 9952:         $ValuesHash{$id.'.'.$key} = $value;
 9953:     }
 9954:     #
 9955:     &Apache::lonnet::appenv(\%ValuesHash);
 9956:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9957: }
 9958: 
 9959: ############################################################
 9960: ############################################################
 9961: 
 9962: =pod
 9963: 
 9964: =item * &DrawXYYGraph()
 9965: 
 9966: Facilitates the plotting of data in an XY graph with two Y axes.
 9967: Puts plot definition data into the users environment in order for 
 9968: graph.png to plot it.  Returns an <img> tag for the plot.
 9969: 
 9970: Inputs:
 9971: 
 9972: =over 4
 9973: 
 9974: =item $Title: string, the title of the plot
 9975: 
 9976: =item $xlabel: string, text describing the X-axis of the plot
 9977: 
 9978: =item $ylabel: string, text describing the Y-axis of the plot
 9979: 
 9980: =item $colors: Array ref containing the hex color codes for the data to be 
 9981: plotted in.  If undefined, default values will be used.
 9982: 
 9983: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9984: 
 9985: =item $Ydata1: The first data set
 9986: 
 9987: =item $Min1: The minimum value of the left Y-axis
 9988: 
 9989: =item $Max1: The maximum value of the left Y-axis
 9990: 
 9991: =item $Ydata2: The second data set
 9992: 
 9993: =item $Min2: The minimum value of the right Y-axis
 9994: 
 9995: =item $Max2: The maximum value of the left Y-axis
 9996: 
 9997: =item %Values: hash indicating or overriding any default values which are 
 9998: passed to graph.png.  
 9999: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
10000: 
10001: =back
10002: 
10003: Returns:
10004: 
10005: An <img> tag which references graph.png and the appropriate identifying
10006: information for the plot.
10007: 
10008: =cut
10009: 
10010: ############################################################
10011: ############################################################
10012: sub DrawXYYGraph {
10013:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
10014:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
10015:     #
10016:     # Create the identifier for the graph
10017:     my $identifier = &get_cgi_id();
10018:     my $id = 'cgi.'.$identifier;
10019:     #
10020:     $Title  = '' if (! defined($Title));
10021:     $xlabel = '' if (! defined($xlabel));
10022:     $ylabel = '' if (! defined($ylabel));
10023:     my %ValuesHash = 
10024:         (
10025:          $id.'.title'  => &escape($Title),
10026:          $id.'.xlabel' => &escape($xlabel),
10027:          $id.'.ylabel' => &escape($ylabel),
10028:          $id.'.labels' => join(',',@$Xlabels),
10029:          $id.'.PlotType' => 'XY',
10030:          $id.'.NumSets' => 2,
10031:          $id.'.two_axes' => 1,
10032:          $id.'.y1_max_value' => $Max1,
10033:          $id.'.y1_min_value' => $Min1,
10034:          $id.'.y2_max_value' => $Max2,
10035:          $id.'.y2_min_value' => $Min2,
10036:          );
10037:     #
10038:     if (defined($colors) && ref($colors) eq 'ARRAY') {
10039:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
10040:     }
10041:     #
10042:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
10043:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
10044:         return '';
10045:     }
10046:     my $NumSets=1;
10047:     foreach my $array ($Ydata1,$Ydata2){
10048:         next if (! ref($array));
10049:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
10050:     }
10051:     #
10052:     # Deal with other parameters
10053:     while (my ($key,$value) = each(%Values)) {
10054:         $ValuesHash{$id.'.'.$key} = $value;
10055:     }
10056:     #
10057:     &Apache::lonnet::appenv(\%ValuesHash);
10058:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
10059: }
10060: 
10061: ############################################################
10062: ############################################################
10063: 
10064: =pod
10065: 
10066: =back 
10067: 
10068: =head1 Statistics helper routines?  
10069: 
10070: Bad place for them but what the hell.
10071: 
10072: =over 4
10073: 
10074: =item * &chartlink()
10075: 
10076: Returns a link to the chart for a specific student.  
10077: 
10078: Inputs:
10079: 
10080: =over 4
10081: 
10082: =item $linktext: The text of the link
10083: 
10084: =item $sname: The students username
10085: 
10086: =item $sdomain: The students domain
10087: 
10088: =back
10089: 
10090: =back
10091: 
10092: =cut
10093: 
10094: ############################################################
10095: ############################################################
10096: sub chartlink {
10097:     my ($linktext, $sname, $sdomain) = @_;
10098:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
10099:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
10100:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
10101:        '">'.$linktext.'</a>';
10102: }
10103: 
10104: #######################################################
10105: #######################################################
10106: 
10107: =pod
10108: 
10109: =head1 Course Environment Routines
10110: 
10111: =over 4
10112: 
10113: =item * &restore_course_settings()
10114: 
10115: =item * &store_course_settings()
10116: 
10117: Restores/Store indicated form parameters from the course environment.
10118: Will not overwrite existing values of the form parameters.
10119: 
10120: Inputs: 
10121: a scalar describing the data (e.g. 'chart', 'problem_analysis')
10122: 
10123: a hash ref describing the data to be stored.  For example:
10124:    
10125: %Save_Parameters = ('Status' => 'scalar',
10126:     'chartoutputmode' => 'scalar',
10127:     'chartoutputdata' => 'scalar',
10128:     'Section' => 'array',
10129:     'Group' => 'array',
10130:     'StudentData' => 'array',
10131:     'Maps' => 'array');
10132: 
10133: Returns: both routines return nothing
10134: 
10135: =back
10136: 
10137: =cut
10138: 
10139: #######################################################
10140: #######################################################
10141: sub store_course_settings {
10142:     return &store_settings($env{'request.course.id'},@_);
10143: }
10144: 
10145: sub store_settings {
10146:     # save to the environment
10147:     # appenv the same items, just to be safe
10148:     my $udom  = $env{'user.domain'};
10149:     my $uname = $env{'user.name'};
10150:     my ($context,$prefix,$Settings) = @_;
10151:     my %SaveHash;
10152:     my %AppHash;
10153:     while (my ($setting,$type) = each(%$Settings)) {
10154:         my $basename = join('.','internal',$context,$prefix,$setting);
10155:         my $envname = 'environment.'.$basename;
10156:         if (exists($env{'form.'.$setting})) {
10157:             # Save this value away
10158:             if ($type eq 'scalar' &&
10159:                 (! exists($env{$envname}) || 
10160:                  $env{$envname} ne $env{'form.'.$setting})) {
10161:                 $SaveHash{$basename} = $env{'form.'.$setting};
10162:                 $AppHash{$envname}   = $env{'form.'.$setting};
10163:             } elsif ($type eq 'array') {
10164:                 my $stored_form;
10165:                 if (ref($env{'form.'.$setting})) {
10166:                     $stored_form = join(',',
10167:                                         map {
10168:                                             &escape($_);
10169:                                         } sort(@{$env{'form.'.$setting}}));
10170:                 } else {
10171:                     $stored_form = 
10172:                         &escape($env{'form.'.$setting});
10173:                 }
10174:                 # Determine if the array contents are the same.
10175:                 if ($stored_form ne $env{$envname}) {
10176:                     $SaveHash{$basename} = $stored_form;
10177:                     $AppHash{$envname}   = $stored_form;
10178:                 }
10179:             }
10180:         }
10181:     }
10182:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
10183:                                           $udom,$uname);
10184:     if ($put_result !~ /^(ok|delayed)/) {
10185:         &Apache::lonnet::logthis('unable to save form parameters, '.
10186:                                  'got error:'.$put_result);
10187:     }
10188:     # Make sure these settings stick around in this session, too
10189:     &Apache::lonnet::appenv(\%AppHash);
10190:     return;
10191: }
10192: 
10193: sub restore_course_settings {
10194:     return &restore_settings($env{'request.course.id'},@_);
10195: }
10196: 
10197: sub restore_settings {
10198:     my ($context,$prefix,$Settings) = @_;
10199:     while (my ($setting,$type) = each(%$Settings)) {
10200:         next if (exists($env{'form.'.$setting}));
10201:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
10202:             '.'.$setting;
10203:         if (exists($env{$envname})) {
10204:             if ($type eq 'scalar') {
10205:                 $env{'form.'.$setting} = $env{$envname};
10206:             } elsif ($type eq 'array') {
10207:                 $env{'form.'.$setting} = [ 
10208:                                            map { 
10209:                                                &unescape($_); 
10210:                                            } split(',',$env{$envname})
10211:                                            ];
10212:             }
10213:         }
10214:     }
10215: }
10216: 
10217: #######################################################
10218: #######################################################
10219: 
10220: =pod
10221: 
10222: =head1 Domain E-mail Routines  
10223: 
10224: =over 4
10225: 
10226: =item * &build_recipient_list()
10227: 
10228: Build recipient lists for five types of e-mail:
10229: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
10230: (d) Help requests, (e) Course requests needing approval,  generated by
10231: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
10232: loncoursequeueadmin.pm respectively.
10233: 
10234: Inputs:
10235: defmail (scalar - email address of default recipient), 
10236: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
10237: defdom (domain for which to retrieve configuration settings),
10238: origmail (scalar - email address of recipient from loncapa.conf, 
10239: i.e., predates configuration by DC via domainprefs.pm 
10240: 
10241: Returns: comma separated list of addresses to which to send e-mail.
10242: 
10243: =back
10244: 
10245: =cut
10246: 
10247: ############################################################
10248: ############################################################
10249: sub build_recipient_list {
10250:     my ($defmail,$mailing,$defdom,$origmail) = @_;
10251:     my @recipients;
10252:     my $otheremails;
10253:     my %domconfig =
10254:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
10255:     if (ref($domconfig{'contacts'}) eq 'HASH') {
10256:         if (exists($domconfig{'contacts'}{$mailing})) {
10257:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
10258:                 my @contacts = ('adminemail','supportemail');
10259:                 foreach my $item (@contacts) {
10260:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
10261:                         my $addr = $domconfig{'contacts'}{$item}; 
10262:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
10263:                             push(@recipients,$addr);
10264:                         }
10265:                     }
10266:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
10267:                 }
10268:             }
10269:         } elsif ($origmail ne '') {
10270:             push(@recipients,$origmail);
10271:         }
10272:     } elsif ($origmail ne '') {
10273:         push(@recipients,$origmail);
10274:     }
10275:     if (defined($defmail)) {
10276:         if ($defmail ne '') {
10277:             push(@recipients,$defmail);
10278:         }
10279:     }
10280:     if ($otheremails) {
10281:         my @others;
10282:         if ($otheremails =~ /,/) {
10283:             @others = split(/,/,$otheremails);
10284:         } else {
10285:             push(@others,$otheremails);
10286:         }
10287:         foreach my $addr (@others) {
10288:             if (!grep(/^\Q$addr\E$/,@recipients)) {
10289:                 push(@recipients,$addr);
10290:             }
10291:         }
10292:     }
10293:     my $recipientlist = join(',',@recipients); 
10294:     return $recipientlist;
10295: }
10296: 
10297: ############################################################
10298: ############################################################
10299: 
10300: =pod
10301: 
10302: =head1 Course Catalog Routines
10303: 
10304: =over 4
10305: 
10306: =item * &gather_categories()
10307: 
10308: Converts category definitions - keys of categories hash stored in  
10309: coursecategories in configuration.db on the primary library server in a 
10310: domain - to an array.  Also generates javascript and idx hash used to 
10311: generate Domain Coordinator interface for editing Course Categories.
10312: 
10313: Inputs:
10314: 
10315: categories (reference to hash of category definitions).
10316: 
10317: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10318:       categories and subcategories).
10319: 
10320: idx (reference to hash of counters used in Domain Coordinator interface for 
10321:       editing Course Categories).
10322: 
10323: jsarray (reference to array of categories used to create Javascript arrays for
10324:          Domain Coordinator interface for editing Course Categories).
10325: 
10326: Returns: nothing
10327: 
10328: Side effects: populates cats, idx and jsarray. 
10329: 
10330: =cut
10331: 
10332: sub gather_categories {
10333:     my ($categories,$cats,$idx,$jsarray) = @_;
10334:     my %counters;
10335:     my $num = 0;
10336:     foreach my $item (keys(%{$categories})) {
10337:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10338:         if ($container eq '' && $depth == 0) {
10339:             $cats->[$depth][$categories->{$item}] = $cat;
10340:         } else {
10341:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
10342:         }
10343:         my ($escitem,$tail) = split(/:/,$item,2);
10344:         if ($counters{$tail} eq '') {
10345:             $counters{$tail} = $num;
10346:             $num ++;
10347:         }
10348:         if (ref($idx) eq 'HASH') {
10349:             $idx->{$item} = $counters{$tail};
10350:         }
10351:         if (ref($jsarray) eq 'ARRAY') {
10352:             push(@{$jsarray->[$counters{$tail}]},$item);
10353:         }
10354:     }
10355:     return;
10356: }
10357: 
10358: =pod
10359: 
10360: =item * &extract_categories()
10361: 
10362: Used to generate breadcrumb trails for course categories.
10363: 
10364: Inputs:
10365: 
10366: categories (reference to hash of category definitions).
10367: 
10368: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10369:       categories and subcategories).
10370: 
10371: trails (reference to array of breacrumb trails for each category).
10372: 
10373: allitems (reference to hash - key is category key 
10374:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10375: 
10376: idx (reference to hash of counters used in Domain Coordinator interface for
10377:       editing Course Categories).
10378: 
10379: jsarray (reference to array of categories used to create Javascript arrays for
10380:          Domain Coordinator interface for editing Course Categories).
10381: 
10382: subcats (reference to hash of arrays containing all subcategories within each 
10383:          category, -recursive)
10384: 
10385: Returns: nothing
10386: 
10387: Side effects: populates trails and allitems hash references.
10388: 
10389: =cut
10390: 
10391: sub extract_categories {
10392:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
10393:     if (ref($categories) eq 'HASH') {
10394:         &gather_categories($categories,$cats,$idx,$jsarray);
10395:         if (ref($cats->[0]) eq 'ARRAY') {
10396:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
10397:                 my $name = $cats->[0][$i];
10398:                 my $item = &escape($name).'::0';
10399:                 my $trailstr;
10400:                 if ($name eq 'instcode') {
10401:                     $trailstr = &mt('Official courses (with institutional codes)');
10402:                 } elsif ($name eq 'communities') {
10403:                     $trailstr = &mt('Communities');
10404:                 } else {
10405:                     $trailstr = $name;
10406:                 }
10407:                 if ($allitems->{$item} eq '') {
10408:                     push(@{$trails},$trailstr);
10409:                     $allitems->{$item} = scalar(@{$trails})-1;
10410:                 }
10411:                 my @parents = ($name);
10412:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
10413:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
10414:                         my $category = $cats->[1]{$name}[$j];
10415:                         if (ref($subcats) eq 'HASH') {
10416:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
10417:                         }
10418:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
10419:                     }
10420:                 } else {
10421:                     if (ref($subcats) eq 'HASH') {
10422:                         $subcats->{$item} = [];
10423:                     }
10424:                 }
10425:             }
10426:         }
10427:     }
10428:     return;
10429: }
10430: 
10431: =pod
10432: 
10433: =item *&recurse_categories()
10434: 
10435: Recursively used to generate breadcrumb trails for course categories.
10436: 
10437: Inputs:
10438: 
10439: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10440:       categories and subcategories).
10441: 
10442: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
10443: 
10444: category (current course category, for which breadcrumb trail is being generated).
10445: 
10446: trails (reference to array of breadcrumb trails for each category).
10447: 
10448: allitems (reference to hash - key is category key
10449:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10450: 
10451: parents (array containing containers directories for current category, 
10452:          back to top level). 
10453: 
10454: Returns: nothing
10455: 
10456: Side effects: populates trails and allitems hash references
10457: 
10458: =cut
10459: 
10460: sub recurse_categories {
10461:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
10462:     my $shallower = $depth - 1;
10463:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
10464:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
10465:             my $name = $cats->[$depth]{$category}[$k];
10466:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10467:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
10468:             if ($allitems->{$item} eq '') {
10469:                 push(@{$trails},$trailstr);
10470:                 $allitems->{$item} = scalar(@{$trails})-1;
10471:             }
10472:             my $deeper = $depth+1;
10473:             push(@{$parents},$category);
10474:             if (ref($subcats) eq 'HASH') {
10475:                 my $subcat = &escape($name).':'.$category.':'.$depth;
10476:                 for (my $j=@{$parents}; $j>=0; $j--) {
10477:                     my $higher;
10478:                     if ($j > 0) {
10479:                         $higher = &escape($parents->[$j]).':'.
10480:                                   &escape($parents->[$j-1]).':'.$j;
10481:                     } else {
10482:                         $higher = &escape($parents->[$j]).'::'.$j;
10483:                     }
10484:                     push(@{$subcats->{$higher}},$subcat);
10485:                 }
10486:             }
10487:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
10488:                                 $subcats);
10489:             pop(@{$parents});
10490:         }
10491:     } else {
10492:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10493:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
10494:         if ($allitems->{$item} eq '') {
10495:             push(@{$trails},$trailstr);
10496:             $allitems->{$item} = scalar(@{$trails})-1;
10497:         }
10498:     }
10499:     return;
10500: }
10501: 
10502: =pod
10503: 
10504: =item *&assign_categories_table()
10505: 
10506: Create a datatable for display of hierarchical categories in a domain,
10507: with checkboxes to allow a course to be categorized. 
10508: 
10509: Inputs:
10510: 
10511: cathash - reference to hash of categories defined for the domain (from
10512:           configuration.db)
10513: 
10514: currcat - scalar with an & separated list of categories assigned to a course. 
10515: 
10516: type    - scalar contains course type (Course or Community).
10517: 
10518: Returns: $output (markup to be displayed) 
10519: 
10520: =cut
10521: 
10522: sub assign_categories_table {
10523:     my ($cathash,$currcat,$type) = @_;
10524:     my $output;
10525:     if (ref($cathash) eq 'HASH') {
10526:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
10527:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
10528:         $maxdepth = scalar(@cats);
10529:         if (@cats > 0) {
10530:             my $itemcount = 0;
10531:             if (ref($cats[0]) eq 'ARRAY') {
10532:                 my @currcategories;
10533:                 if ($currcat ne '') {
10534:                     @currcategories = split('&',$currcat);
10535:                 }
10536:                 my $table;
10537:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
10538:                     my $parent = $cats[0][$i];
10539:                     next if ($parent eq 'instcode');
10540:                     if ($type eq 'Community') {
10541:                         next unless ($parent eq 'communities');
10542:                     } else {
10543:                         next if ($parent eq 'communities');
10544:                     }
10545:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10546:                     my $item = &escape($parent).'::0';
10547:                     my $checked = '';
10548:                     if (@currcategories > 0) {
10549:                         if (grep(/^\Q$item\E$/,@currcategories)) {
10550:                             $checked = ' checked="checked"';
10551:                         }
10552:                     }
10553:                     my $parent_title = $parent;
10554:                     if ($parent eq 'communities') {
10555:                         $parent_title = &mt('Communities');
10556:                     }
10557:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
10558:                               '<input type="checkbox" name="usecategory" value="'.
10559:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
10560:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
10561:                     my $depth = 1;
10562:                     push(@path,$parent);
10563:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
10564:                     pop(@path);
10565:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10566:                     $itemcount ++;
10567:                 }
10568:                 if ($itemcount) {
10569:                     $output = &Apache::loncommon::start_data_table().
10570:                               $table.
10571:                               &Apache::loncommon::end_data_table();
10572:                 }
10573:             }
10574:         }
10575:     }
10576:     return $output;
10577: }
10578: 
10579: =pod
10580: 
10581: =item *&assign_category_rows()
10582: 
10583: Create a datatable row for display of nested categories in a domain,
10584: with checkboxes to allow a course to be categorized,called recursively.
10585: 
10586: Inputs:
10587: 
10588: itemcount - track row number for alternating colors
10589: 
10590: cats - reference to array of arrays/hashes which encapsulates hierarchy of
10591:       categories and subcategories.
10592: 
10593: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
10594: 
10595: parent - parent of current category item
10596: 
10597: path - Array containing all categories back up through the hierarchy from the
10598:        current category to the top level.
10599: 
10600: currcategories - reference to array of current categories assigned to the course
10601: 
10602: Returns: $output (markup to be displayed).
10603: 
10604: =cut
10605: 
10606: sub assign_category_rows {
10607:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
10608:     my ($text,$name,$item,$chgstr);
10609:     if (ref($cats) eq 'ARRAY') {
10610:         my $maxdepth = scalar(@{$cats});
10611:         if (ref($cats->[$depth]) eq 'HASH') {
10612:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10613:                 my $numchildren = @{$cats->[$depth]{$parent}};
10614:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10615:                 $text .= '<td><table class="LC_datatable">';
10616:                 for (my $j=0; $j<$numchildren; $j++) {
10617:                     $name = $cats->[$depth]{$parent}[$j];
10618:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
10619:                     my $deeper = $depth+1;
10620:                     my $checked = '';
10621:                     if (ref($currcategories) eq 'ARRAY') {
10622:                         if (@{$currcategories} > 0) {
10623:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
10624:                                 $checked = ' checked="checked"';
10625:                             }
10626:                         }
10627:                     }
10628:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
10629:                              '<input type="checkbox" name="usecategory" value="'.
10630:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
10631:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
10632:                              '</td><td>';
10633:                     if (ref($path) eq 'ARRAY') {
10634:                         push(@{$path},$name);
10635:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10636:                         pop(@{$path});
10637:                     }
10638:                     $text .= '</td></tr>';
10639:                 }
10640:                 $text .= '</table></td>';
10641:             }
10642:         }
10643:     }
10644:     return $text;
10645: }
10646: 
10647: ############################################################
10648: ############################################################
10649: 
10650: 
10651: sub commit_customrole {
10652:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10653:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10654:                          ($start?', '.&mt('starting').' '.localtime($start):'').
10655:                          ($end?', ending '.localtime($end):'').': <b>'.
10656:               &Apache::lonnet::assigncustomrole(
10657:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10658:                  '</b><br />';
10659:     return $output;
10660: }
10661: 
10662: sub commit_standardrole {
10663:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10664:     my ($output,$logmsg,$linefeed);
10665:     if ($context eq 'auto') {
10666:         $linefeed = "\n";
10667:     } else {
10668:         $linefeed = "<br />\n";
10669:     }  
10670:     if ($three eq 'st') {
10671:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10672:                                          $one,$two,$sec,$context);
10673:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
10674:             ($result eq 'unknown_course') || ($result eq 'refused')) {
10675:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
10676:         } else {
10677:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10678:                ($start?', '.&mt('starting').' '.localtime($start):'').
10679:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10680:             if ($context eq 'auto') {
10681:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10682:             } else {
10683:                $output .= '<b>'.$result.'</b>'.$linefeed.
10684:                &mt('Add to classlist').': <b>ok</b>';
10685:             }
10686:             $output .= $linefeed;
10687:         }
10688:     } else {
10689:         $output = &mt('Assigning').' '.$three.' in '.$url.
10690:                ($start?', '.&mt('starting').' '.localtime($start):'').
10691:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10692:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10693:         if ($context eq 'auto') {
10694:             $output .= $result.$linefeed;
10695:         } else {
10696:             $output .= '<b>'.$result.'</b>'.$linefeed;
10697:         }
10698:     }
10699:     return $output;
10700: }
10701: 
10702: sub commit_studentrole {
10703:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10704:     my ($result,$linefeed,$oldsecurl,$newsecurl);
10705:     if ($context eq 'auto') {
10706:         $linefeed = "\n";
10707:     } else {
10708:         $linefeed = '<br />'."\n";
10709:     }
10710:     if (defined($one) && defined($two)) {
10711:         my $cid=$one.'_'.$two;
10712:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10713:         my $secchange = 0;
10714:         my $expire_role_result;
10715:         my $modify_section_result;
10716:         if ($oldsec ne '-1') { 
10717:             if ($oldsec ne $sec) {
10718:                 $secchange = 1;
10719:                 my $now = time;
10720:                 my $uurl='/'.$cid;
10721:                 $uurl=~s/\_/\//g;
10722:                 if ($oldsec) {
10723:                     $uurl.='/'.$oldsec;
10724:                 }
10725:                 $oldsecurl = $uurl;
10726:                 $expire_role_result = 
10727:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10728:                 if ($env{'request.course.sec'} ne '') { 
10729:                     if ($expire_role_result eq 'refused') {
10730:                         my @roles = ('st');
10731:                         my @statuses = ('previous');
10732:                         my @roledoms = ($one);
10733:                         my $withsec = 1;
10734:                         my %roleshash = 
10735:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10736:                                               \@statuses,\@roles,\@roledoms,$withsec);
10737:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10738:                             my ($oldstart,$oldend) = 
10739:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10740:                             if ($oldend > 0 && $oldend <= $now) {
10741:                                 $expire_role_result = 'ok';
10742:                             }
10743:                         }
10744:                     }
10745:                 }
10746:                 $result = $expire_role_result;
10747:             }
10748:         }
10749:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10750:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10751:             if ($modify_section_result =~ /^ok/) {
10752:                 if ($secchange == 1) {
10753:                     if ($sec eq '') {
10754:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10755:                     } else {
10756:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10757:                     }
10758:                 } elsif ($oldsec eq '-1') {
10759:                     if ($sec eq '') {
10760:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10761:                     } else {
10762:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10763:                     }
10764:                 } else {
10765:                     if ($sec eq '') {
10766:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10767:                     } else {
10768:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10769:                     }
10770:                 }
10771:             } else {
10772:                 if ($secchange) {       
10773:                     $$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;
10774:                 } else {
10775:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10776:                 }
10777:             }
10778:             $result = $modify_section_result;
10779:         } elsif ($secchange == 1) {
10780:             if ($oldsec eq '') {
10781:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10782:             } else {
10783:                 $$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;
10784:             }
10785:             if ($expire_role_result eq 'refused') {
10786:                 my $newsecurl = '/'.$cid;
10787:                 $newsecurl =~ s/\_/\//g;
10788:                 if ($sec ne '') {
10789:                     $newsecurl.='/'.$sec;
10790:                 }
10791:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10792:                     if ($sec eq '') {
10793:                         $$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;
10794:                     } else {
10795:                         $$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;
10796:                     }
10797:                 }
10798:             }
10799:         }
10800:     } else {
10801:         $$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;
10802:         $result = "error: incomplete course id\n";
10803:     }
10804:     return $result;
10805: }
10806: 
10807: ############################################################
10808: ############################################################
10809: 
10810: sub check_clone {
10811:     my ($args,$linefeed) = @_;
10812:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10813:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10814:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10815:     my $clonemsg;
10816:     my $can_clone = 0;
10817:     my $lctype = lc($args->{'crstype'});
10818:     if ($lctype ne 'community') {
10819:         $lctype = 'course';
10820:     }
10821:     if ($clonehome eq 'no_host') {
10822:         if ($args->{'crstype'} eq 'Community') {
10823:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10824:         } else {
10825:             $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'});
10826:         }     
10827:     } else {
10828: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10829:         if ($args->{'crstype'} eq 'Community') {
10830:             if ($clonedesc{'type'} ne 'Community') {
10831:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10832:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10833:             }
10834:         }
10835: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10836:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10837: 	    $can_clone = 1;
10838: 	} else {
10839: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10840: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10841: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10842:             if (grep(/^\*$/,@cloners)) {
10843:                 $can_clone = 1;
10844:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10845:                 $can_clone = 1;
10846:             } else {
10847:                 my $ccrole = 'cc';
10848:                 if ($args->{'crstype'} eq 'Community') {
10849:                     $ccrole = 'co';
10850:                 }
10851: 	        my %roleshash =
10852: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10853: 					 $args->{'ccdomain'},
10854:                                          'userroles',['active'],[$ccrole],
10855: 					 [$args->{'clonedomain'}]);
10856: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10857:                     $can_clone = 1;
10858:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10859:                     $can_clone = 1;
10860:                 } else {
10861:                     if ($args->{'crstype'} eq 'Community') {
10862:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
10863:                     } else {
10864:                         $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'});
10865:                     }
10866: 	        }
10867: 	    }
10868:         }
10869:     }
10870:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
10871: }
10872: 
10873: sub construct_course {
10874:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10875:     my $outcome;
10876:     my $linefeed =  '<br />'."\n";
10877:     if ($context eq 'auto') {
10878:         $linefeed = "\n";
10879:     }
10880: 
10881: #
10882: # Are we cloning?
10883: #
10884:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
10885:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10886: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10887: 	if ($context ne 'auto') {
10888:             if ($clonemsg ne '') {
10889: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10890:             }
10891: 	}
10892: 	$outcome .= $clonemsg.$linefeed;
10893: 
10894:         if (!$can_clone) {
10895: 	    return (0,$outcome);
10896: 	}
10897:     }
10898: 
10899: #
10900: # Open course
10901: #
10902:     my $crstype = lc($args->{'crstype'});
10903:     my %cenv=();
10904:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10905:                                              $args->{'cdescr'},
10906:                                              $args->{'curl'},
10907:                                              $args->{'course_home'},
10908:                                              $args->{'nonstandard'},
10909:                                              $args->{'crscode'},
10910:                                              $args->{'ccuname'}.':'.
10911:                                              $args->{'ccdomain'},
10912:                                              $args->{'crstype'},
10913:                                              $cnum,$context,$category);
10914: 
10915:     # Note: The testing routines depend on this being output; see 
10916:     # Utils::Course. This needs to at least be output as a comment
10917:     # if anyone ever decides to not show this, and Utils::Course::new
10918:     # will need to be suitably modified.
10919:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10920:     if ($$courseid =~ /^error:/) {
10921:         return (0,$outcome);
10922:     }
10923: 
10924: #
10925: # Check if created correctly
10926: #
10927:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10928:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10929:     if ($crsuhome eq 'no_host') {
10930:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10931:         return (0,$outcome);
10932:     }
10933:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10934: 
10935: #
10936: # Do the cloning
10937: #   
10938:     if ($can_clone && $cloneid) {
10939: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10940: 	if ($context ne 'auto') {
10941: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10942: 	}
10943: 	$outcome .= $clonemsg.$linefeed;
10944: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10945: # Copy all files
10946: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10947: # Restore URL
10948: 	$cenv{'url'}=$oldcenv{'url'};
10949: # Restore title
10950: 	$cenv{'description'}=$oldcenv{'description'};
10951: # Restore creation date, creator and creation context.
10952:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
10953:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
10954:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
10955: # Mark as cloned
10956: 	$cenv{'clonedfrom'}=$cloneid;
10957: # Need to clone grading mode
10958:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10959:         $cenv{'grading'}=$newenv{'grading'};
10960: # Do not clone these environment entries
10961:         &Apache::lonnet::del('environment',
10962:                   ['default_enrollment_start_date',
10963:                    'default_enrollment_end_date',
10964:                    'question.email',
10965:                    'policy.email',
10966:                    'comment.email',
10967:                    'pch.users.denied',
10968:                    'plc.users.denied',
10969:                    'hidefromcat',
10970:                    'categories'],
10971:                    $$crsudom,$$crsunum);
10972:     }
10973: 
10974: #
10975: # Set environment (will override cloned, if existing)
10976: #
10977:     my @sections = ();
10978:     my @xlists = ();
10979:     if ($args->{'crstype'}) {
10980:         $cenv{'type'}=$args->{'crstype'};
10981:     }
10982:     if ($args->{'crsid'}) {
10983:         $cenv{'courseid'}=$args->{'crsid'};
10984:     }
10985:     if ($args->{'crscode'}) {
10986:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10987:     }
10988:     if ($args->{'crsquota'} ne '') {
10989:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10990:     } else {
10991:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10992:     }
10993:     if ($args->{'ccuname'}) {
10994:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10995:                                         ':'.$args->{'ccdomain'};
10996:     } else {
10997:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10998:     }
10999:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
11000:     if ($args->{'crssections'}) {
11001:         $cenv{'internal.sectionnums'} = '';
11002:         if ($args->{'crssections'} =~ m/,/) {
11003:             @sections = split/,/,$args->{'crssections'};
11004:         } else {
11005:             $sections[0] = $args->{'crssections'};
11006:         }
11007:         if (@sections > 0) {
11008:             foreach my $item (@sections) {
11009:                 my ($sec,$gp) = split/:/,$item;
11010:                 my $class = $args->{'crscode'}.$sec;
11011:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
11012:                 $cenv{'internal.sectionnums'} .= $item.',';
11013:                 unless ($addcheck eq 'ok') {
11014:                     push @badclasses, $class;
11015:                 }
11016:             }
11017:             $cenv{'internal.sectionnums'} =~ s/,$//;
11018:         }
11019:     }
11020: # do not hide course coordinator from staff listing, 
11021: # even if privileged
11022:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11023: # add crosslistings
11024:     if ($args->{'crsxlist'}) {
11025:         $cenv{'internal.crosslistings'}='';
11026:         if ($args->{'crsxlist'} =~ m/,/) {
11027:             @xlists = split/,/,$args->{'crsxlist'};
11028:         } else {
11029:             $xlists[0] = $args->{'crsxlist'};
11030:         }
11031:         if (@xlists > 0) {
11032:             foreach my $item (@xlists) {
11033:                 my ($xl,$gp) = split/:/,$item;
11034:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
11035:                 $cenv{'internal.crosslistings'} .= $item.',';
11036:                 unless ($addcheck eq 'ok') {
11037:                     push @badclasses, $xl;
11038:                 }
11039:             }
11040:             $cenv{'internal.crosslistings'} =~ s/,$//;
11041:         }
11042:     }
11043:     if ($args->{'autoadds'}) {
11044:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
11045:     }
11046:     if ($args->{'autodrops'}) {
11047:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
11048:     }
11049: # check for notification of enrollment changes
11050:     my @notified = ();
11051:     if ($args->{'notify_owner'}) {
11052:         if ($args->{'ccuname'} ne '') {
11053:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
11054:         }
11055:     }
11056:     if ($args->{'notify_dc'}) {
11057:         if ($uname ne '') { 
11058:             push(@notified,$uname.':'.$udom);
11059:         }
11060:     }
11061:     if (@notified > 0) {
11062:         my $notifylist;
11063:         if (@notified > 1) {
11064:             $notifylist = join(',',@notified);
11065:         } else {
11066:             $notifylist = $notified[0];
11067:         }
11068:         $cenv{'internal.notifylist'} = $notifylist;
11069:     }
11070:     if (@badclasses > 0) {
11071:         my %lt=&Apache::lonlocal::texthash(
11072:                 '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',
11073:                 'dnhr' => 'does not have rights to access enrollment in these classes',
11074:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
11075:         );
11076:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
11077:                            ' ('.$lt{'adby'}.')';
11078:         if ($context eq 'auto') {
11079:             $outcome .= $badclass_msg.$linefeed;
11080:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
11081:             foreach my $item (@badclasses) {
11082:                 if ($context eq 'auto') {
11083:                     $outcome .= " - $item\n";
11084:                 } else {
11085:                     $outcome .= "<li>$item</li>\n";
11086:                 }
11087:             }
11088:             if ($context eq 'auto') {
11089:                 $outcome .= $linefeed;
11090:             } else {
11091:                 $outcome .= "</ul><br /><br /></div>\n";
11092:             }
11093:         } 
11094:     }
11095:     if ($args->{'no_end_date'}) {
11096:         $args->{'endaccess'} = 0;
11097:     }
11098:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
11099:     $cenv{'internal.autoend'}=$args->{'enrollend'};
11100:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
11101:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
11102:     if ($args->{'showphotos'}) {
11103:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
11104:     }
11105:     $cenv{'internal.authtype'} = $args->{'authtype'};
11106:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
11107:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
11108:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
11109:             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'); 
11110:             if ($context eq 'auto') {
11111:                 $outcome .= $krb_msg;
11112:             } else {
11113:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
11114:             }
11115:             $outcome .= $linefeed;
11116:         }
11117:     }
11118:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
11119:        if ($args->{'setpolicy'}) {
11120:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11121:        }
11122:        if ($args->{'setcontent'}) {
11123:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11124:        }
11125:     }
11126:     if ($args->{'reshome'}) {
11127: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
11128: 	$cenv{'reshome'}=~s/\/+$/\//;
11129:     }
11130: #
11131: # course has keyed access
11132: #
11133:     if ($args->{'setkeys'}) {
11134:        $cenv{'keyaccess'}='yes';
11135:     }
11136: # if specified, key authority is not course, but user
11137: # only active if keyaccess is yes
11138:     if ($args->{'keyauth'}) {
11139: 	my ($user,$domain) = split(':',$args->{'keyauth'});
11140: 	$user = &LONCAPA::clean_username($user);
11141: 	$domain = &LONCAPA::clean_username($domain);
11142: 	if ($user ne '' && $domain ne '') {
11143: 	    $cenv{'keyauth'}=$user.':'.$domain;
11144: 	}
11145:     }
11146: 
11147:     if ($args->{'disresdis'}) {
11148:         $cenv{'pch.roles.denied'}='st';
11149:     }
11150:     if ($args->{'disablechat'}) {
11151:         $cenv{'plc.roles.denied'}='st';
11152:     }
11153: 
11154:     # Record we've not yet viewed the Course Initialization Helper for this 
11155:     # course
11156:     $cenv{'course.helper.not.run'} = 1;
11157:     #
11158:     # Use new Randomseed
11159:     #
11160:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
11161:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
11162:     #
11163:     # The encryption code and receipt prefix for this course
11164:     #
11165:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
11166:     $cenv{'internal.encpref'}=100+int(9*rand(99));
11167:     #
11168:     # By default, use standard grading
11169:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
11170: 
11171:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
11172:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
11173: #
11174: # Open all assignments
11175: #
11176:     if ($args->{'openall'}) {
11177:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
11178:        my %storecontent = ($storeunder         => time,
11179:                            $storeunder.'.type' => 'date_start');
11180:        
11181:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
11182:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
11183:    }
11184: #
11185: # Set first page
11186: #
11187:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
11188: 	    || ($cloneid)) {
11189: 	use LONCAPA::map;
11190: 	$outcome .= &mt('Setting first resource').': ';
11191: 
11192: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
11193:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
11194: 
11195:         $outcome .= ($fatal?$errtext:'read ok').' - ';
11196:         my $title; my $url;
11197:         if ($args->{'firstres'} eq 'syl') {
11198: 	    $title=&mt('Syllabus');
11199:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
11200:         } else {
11201:             $title=&mt('Table of Contents');
11202:             $url='/adm/navmaps';
11203:         }
11204: 
11205:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
11206: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
11207: 
11208: 	if ($errtext) { $fatal=2; }
11209:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
11210:     }
11211: 
11212:     return (1,$outcome);
11213: }
11214: 
11215: ############################################################
11216: ############################################################
11217: 
11218: sub course_type {
11219:     my ($cid) = @_;
11220:     if (!defined($cid)) {
11221:         $cid = $env{'request.course.id'};
11222:     }
11223:     if (defined($env{'course.'.$cid.'.type'})) {
11224:         return $env{'course.'.$cid.'.type'};
11225:     } else {
11226:         return 'Course';
11227:     }
11228: }
11229: 
11230: sub group_term {
11231:     my $crstype = &course_type();
11232:     my %names = (
11233:                   'Course' => 'group',
11234:                   'Community' => 'group',
11235:                 );
11236:     return $names{$crstype};
11237: }
11238: 
11239: sub course_types {
11240:     my @types = ('official','unofficial','community');
11241:     my %typename = (
11242:                          official   => 'Official course',
11243:                          unofficial => 'Unofficial course',
11244:                          community  => 'Community',
11245:                    );
11246:     return (\@types,\%typename);
11247: }
11248: 
11249: sub icon {
11250:     my ($file)=@_;
11251:     my $curfext = lc((split(/\./,$file))[-1]);
11252:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
11253:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
11254:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
11255: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
11256: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11257: 	            $curfext.".gif") {
11258: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11259: 		$curfext.".gif";
11260: 	}
11261:     }
11262:     return &lonhttpdurl($iconname);
11263: } 
11264: 
11265: sub lonhttpdurl {
11266: #
11267: # Had been used for "small fry" static images on separate port 8080.
11268: # Modify here if lightweight http functionality desired again.
11269: # Currently eliminated due to increasing firewall issues.
11270: #
11271:     my ($url)=@_;
11272:     return $url;
11273: }
11274: 
11275: sub connection_aborted {
11276:     my ($r)=@_;
11277:     $r->print(" ");$r->rflush();
11278:     my $c = $r->connection;
11279:     return $c->aborted();
11280: }
11281: 
11282: #    Escapes strings that may have embedded 's that will be put into
11283: #    strings as 'strings'.
11284: sub escape_single {
11285:     my ($input) = @_;
11286:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
11287:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
11288:     return $input;
11289: }
11290: 
11291: #  Same as escape_single, but escape's "'s  This 
11292: #  can be used for  "strings"
11293: sub escape_double {
11294:     my ($input) = @_;
11295:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
11296:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
11297:     return $input;
11298: }
11299:  
11300: #   Escapes the last element of a full URL.
11301: sub escape_url {
11302:     my ($url)   = @_;
11303:     my @urlslices = split(/\//, $url,-1);
11304:     my $lastitem = &escape(pop(@urlslices));
11305:     return join('/',@urlslices).'/'.$lastitem;
11306: }
11307: 
11308: sub compare_arrays {
11309:     my ($arrayref1,$arrayref2) = @_;
11310:     my (@difference,%count);
11311:     @difference = ();
11312:     %count = ();
11313:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
11314:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
11315:         foreach my $element (keys(%count)) {
11316:             if ($count{$element} == 1) {
11317:                 push(@difference,$element);
11318:             }
11319:         }
11320:     }
11321:     return @difference;
11322: }
11323: 
11324: # -------------------------------------------------------- Initialize user login
11325: sub init_user_environment {
11326:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
11327:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
11328: 
11329:     my $public=($username eq 'public' && $domain eq 'public');
11330: 
11331: # See if old ID present, if so, remove
11332: 
11333:     my ($filename,$cookie,$userroles);
11334:     my $now=time;
11335: 
11336:     if ($public) {
11337: 	my $max_public=100;
11338: 	my $oldest;
11339: 	my $oldest_time=0;
11340: 	for(my $next=1;$next<=$max_public;$next++) {
11341: 	    if (-e $lonids."/publicuser_$next.id") {
11342: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
11343: 		if ($mtime<$oldest_time || !$oldest_time) {
11344: 		    $oldest_time=$mtime;
11345: 		    $oldest=$next;
11346: 		}
11347: 	    } else {
11348: 		$cookie="publicuser_$next";
11349: 		last;
11350: 	    }
11351: 	}
11352: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
11353:     } else {
11354: 	# if this isn't a robot, kill any existing non-robot sessions
11355: 	if (!$args->{'robot'}) {
11356: 	    opendir(DIR,$lonids);
11357: 	    while ($filename=readdir(DIR)) {
11358: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
11359: 		    unlink($lonids.'/'.$filename);
11360: 		}
11361: 	    }
11362: 	    closedir(DIR);
11363: 	}
11364: # Give them a new cookie
11365: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
11366: 		                   : $now.$$.int(rand(10000)));
11367: 	$cookie="$username\_$id\_$domain\_$authhost";
11368:     
11369: # Initialize roles
11370: 
11371: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
11372:     }
11373: # ------------------------------------ Check browser type and MathML capability
11374: 
11375:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
11376:         $clientunicode,$clientos) = &decode_user_agent($r);
11377: 
11378: # ------------------------------------------------------------- Get environment
11379: 
11380:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
11381:     my ($tmp) = keys(%userenv);
11382:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11383: 	# default remote control to off
11384: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
11385:     } else {
11386: 	undef(%userenv);
11387:     }
11388:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
11389: 	$form->{'interface'}=$userenv{'interface'};
11390:     }
11391:     $env{'environment.remote'}=$userenv{'remote'};
11392:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
11393: 
11394: # --------------- Do not trust query string to be put directly into environment
11395:     foreach my $option ('interface','localpath','localres') {
11396:         $form->{$option}=~s/[\n\r\=]//gs;
11397:     }
11398: # --------------------------------------------------------- Write first profile
11399: 
11400:     {
11401: 	my %initial_env = 
11402: 	    ("user.name"          => $username,
11403: 	     "user.domain"        => $domain,
11404: 	     "user.home"          => $authhost,
11405: 	     "browser.type"       => $clientbrowser,
11406: 	     "browser.version"    => $clientversion,
11407: 	     "browser.mathml"     => $clientmathml,
11408: 	     "browser.unicode"    => $clientunicode,
11409: 	     "browser.os"         => $clientos,
11410: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
11411: 	     "request.course.fn"  => '',
11412: 	     "request.course.uri" => '',
11413: 	     "request.course.sec" => '',
11414: 	     "request.role"       => 'cm',
11415: 	     "request.role.adv"   => $env{'user.adv'},
11416: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
11417: 
11418:         if ($form->{'localpath'}) {
11419: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
11420: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
11421:         }
11422: 	
11423: 	if ($public) {
11424: 	    $initial_env{"environment.remote"} = "off";
11425: 	}
11426: 	if ($form->{'interface'}) {
11427: 	    $form->{'interface'}=~s/\W//gs;
11428: 	    $initial_env{"browser.interface"} = $form->{'interface'};
11429: 	    $env{'browser.interface'}=$form->{'interface'};
11430: 	}
11431:         my %is_adv = ( is_adv => $env{'user.adv'} );
11432:         my %domdef;
11433:         unless ($domain eq 'public') {
11434:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
11435:         }
11436: 
11437:         foreach my $tool ('aboutme','blog','portfolio') {
11438:             $userenv{'availabletools.'.$tool} = 
11439:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
11440:                                                   undef,\%userenv,\%domdef,\%is_adv);
11441:         }
11442: 
11443:         foreach my $crstype ('official','unofficial','community') {
11444:             $userenv{'canrequest.'.$crstype} =
11445:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
11446:                                                   'reload','requestcourses',
11447:                                                   \%userenv,\%domdef,\%is_adv);
11448:         }
11449: 
11450: 	$env{'user.environment'} = "$lonids/$cookie.id";
11451: 	
11452: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
11453: 		 &GDBM_WRCREAT(),0640)) {
11454: 	    &_add_to_env(\%disk_env,\%initial_env);
11455: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
11456: 	    &_add_to_env(\%disk_env,$userroles);
11457: 	    if (ref($args->{'extra_env'})) {
11458: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
11459: 	    }
11460: 	    untie(%disk_env);
11461: 	} else {
11462: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
11463: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
11464: 	    return 'error: '.$!;
11465: 	}
11466:     }
11467:     $env{'request.role'}='cm';
11468:     $env{'request.role.adv'}=$env{'user.adv'};
11469:     $env{'browser.type'}=$clientbrowser;
11470: 
11471:     return $cookie;
11472: 
11473: }
11474: 
11475: sub _add_to_env {
11476:     my ($idf,$env_data,$prefix) = @_;
11477:     if (ref($env_data) eq 'HASH') {
11478:         while (my ($key,$value) = each(%$env_data)) {
11479: 	    $idf->{$prefix.$key} = $value;
11480: 	    $env{$prefix.$key}   = $value;
11481:         }
11482:     }
11483: }
11484: 
11485: # --- Get the symbolic name of a problem and the url
11486: sub get_symb {
11487:     my ($request,$silent) = @_;
11488:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11489:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
11490:     if ($symb eq '') {
11491:         if (!$silent) {
11492:             $request->print("Unable to handle ambiguous references:$url:.");
11493:             return ();
11494:         }
11495:     }
11496:     &Apache::lonenc::check_decrypt(\$symb);
11497:     return ($symb);
11498: }
11499: 
11500: # --------------------------------------------------------------Get annotation
11501: 
11502: sub get_annotation {
11503:     my ($symb,$enc) = @_;
11504: 
11505:     my $key = $symb;
11506:     if (!$enc) {
11507:         $key =
11508:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
11509:     }
11510:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
11511:     return $annotation{$key};
11512: }
11513: 
11514: sub clean_symb {
11515:     my ($symb,$delete_enc) = @_;
11516: 
11517:     &Apache::lonenc::check_decrypt(\$symb);
11518:     my $enc = $env{'request.enc'};
11519:     if ($delete_enc) {
11520:         delete($env{'request.enc'});
11521:     }
11522: 
11523:     return ($symb,$enc);
11524: }
11525: 
11526: sub build_release_hashes {
11527:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
11528:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
11529:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
11530:                   (ref($randomizetry) eq 'HASH'));
11531:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
11532:         my ($item,$name,$value) = split(/:/,$key);
11533:         if ($item eq 'parameter') {
11534:             if (ref($checkparms->{$name}) eq 'ARRAY') {
11535:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
11536:                     push(@{$checkparms->{$name}},$value);
11537:                 }
11538:             } else {
11539:                 push(@{$checkparms->{$name}},$value);
11540:             }
11541:         } elsif ($item eq 'resourcetag') {
11542:             if ($name eq 'responsetype') {
11543:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
11544:             }
11545:         } elsif ($item eq 'course') {
11546:             if ($name eq 'crstype') {
11547:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
11548:             }
11549:         }
11550:     }
11551:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
11552:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
11553:     return;
11554: }
11555: 
11556: =pod
11557: 
11558: =back
11559: 
11560: =cut
11561: 
11562: 1;
11563: __END__;
11564: 

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