File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.948.2.29: download - view: text, annotated - select for diffs
Sat May 28 00:02:38 2011 UTC (12 years, 11 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0
- Backport 1.1007.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.948.2.29 2011/05/28 00:02:38 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,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: 	if (roleflag) { url+="&roles=1"; }
  426:         if (courseadvonly) { url+="&courseadvonly=1"; }
  427:         var title = 'Student_Browser';
  428:         var options = 'scrollbars=1,resizable=1,menubar=0';
  429:         options += ',width=700,height=600';
  430:         stdeditbrowser = open(url,title,options,'1');
  431:         stdeditbrowser.focus();
  432:     }
  433: // ]]>
  434: </script>
  435: ENDSTDBRW
  436: }
  437: 
  438: sub selectstudent_link {
  439:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
  440:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
  441:    if ($env{'request.course.id'}) {  
  442:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  443: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  444: 					'/'.$env{'request.course.sec'})) {
  445: 	   return '';
  446:        }
  447:        if ($courseadvonly)  {
  448:            $callargs .= ",'',1,1";
  449:        }
  450:        return '<span class="LC_nobreak">'.
  451:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  452:               &mt('Select User').'</a></span>';
  453:    }
  454:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  455:        $callargs .= ",1"; 
  456:        return '<span class="LC_nobreak">'.
  457:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  458:               &mt('Select User').'</a></span>';
  459:    }
  460:    return '';
  461: }
  462: 
  463: sub authorbrowser_javascript {
  464:     return <<"ENDAUTHORBRW";
  465: <script type="text/javascript" language="JavaScript">
  466: // <![CDATA[
  467: var stdeditbrowser;
  468: 
  469: function openauthorbrowser(formname,udom) {
  470:     var url = '/adm/pickauthor?';
  471:     url += 'form='+formname+'&roledom='+udom;
  472:     var title = 'Author_Browser';
  473:     var options = 'scrollbars=1,resizable=1,menubar=0';
  474:     options += ',width=700,height=600';
  475:     stdeditbrowser = open(url,title,options,'1');
  476:     stdeditbrowser.focus();
  477: }
  478: 
  479: // ]]>
  480: </script>
  481: ENDAUTHORBRW
  482: }
  483: 
  484: sub coursebrowser_javascript {
  485:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  486:     my $wintitle = 'Course_Browser';
  487:     if ($crstype eq 'Community') {
  488:         $wintitle = 'Community_Browser';
  489:     }
  490:     my $id_functions = &javascript_index_functions();
  491:     my $output = '
  492: <script type="text/javascript" language="JavaScript">
  493: // <![CDATA[
  494:     var stdeditbrowser;'."\n";
  495: 
  496:     $output .= <<"ENDSTDBRW";
  497:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  498:         var url = '/adm/pickcourse?';
  499:         var formid = getFormIdByName(formname);
  500:         var domainfilter = getDomainFromSelectbox(formname,udom);
  501:         if (domainfilter != null) {
  502:            if (domainfilter != '') {
  503:                url += 'domainfilter='+domainfilter+'&';
  504: 	   }
  505:         }
  506:         url += 'form=' + formname + '&cnumelement='+uname+
  507: 	                            '&cdomelement='+udom+
  508:                                     '&cnameelement='+desc;
  509:         if (extra_element !=null && extra_element != '') {
  510:             if (formname == 'rolechoice' || formname == 'studentform') {
  511:                 url += '&roleelement='+extra_element;
  512:                 if (domainfilter == null || domainfilter == '') {
  513:                     url += '&domainfilter='+extra_element;
  514:                 }
  515:             }
  516:             else {
  517:                 if (formname == 'portform') {
  518:                     url += '&setroles='+extra_element;
  519:                 } else {
  520:                     if (formname == 'rules') {
  521:                         url += '&fixeddom='+extra_element; 
  522:                     }
  523:                 }
  524:             }     
  525:         }
  526:         if (type != null && type != '') {
  527:             url += '&type='+type;
  528:         }
  529:         if (type_elem != null && type_elem != '') {
  530:             url += '&typeelement='+type_elem;
  531:         }
  532:         if (formname == 'ccrs') {
  533:             var ownername = document.forms[formid].ccuname.value;
  534:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  535:             url += '&cloner='+ownername+':'+ownerdom;
  536:         }
  537:         if (multflag !=null && multflag != '') {
  538:             url += '&multiple='+multflag;
  539:         }
  540:         var title = '$wintitle';
  541:         var options = 'scrollbars=1,resizable=1,menubar=0';
  542:         options += ',width=700,height=600';
  543:         stdeditbrowser = open(url,title,options,'1');
  544:         stdeditbrowser.focus();
  545:     }
  546: $id_functions
  547: ENDSTDBRW
  548:     if (($sec_element ne '') || ($role_element ne '')) {
  549:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  550:     }
  551:     $output .= '
  552: // ]]>
  553: </script>';
  554:     return $output;
  555: }
  556: 
  557: sub javascript_index_functions {
  558:     return <<"ENDJS";
  559: 
  560: function getFormIdByName(formname) {
  561:     for (var i=0;i<document.forms.length;i++) {
  562:         if (document.forms[i].name == formname) {
  563:             return i;
  564:         }
  565:     }
  566:     return -1;
  567: }
  568: 
  569: function getIndexByName(formid,item) {
  570:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  571:         if (document.forms[formid].elements[i].name == item) {
  572:             return i;
  573:         }
  574:     }
  575:     return -1;
  576: }
  577: 
  578: function getDomainFromSelectbox(formname,udom) {
  579:     var userdom;
  580:     var formid = getFormIdByName(formname);
  581:     if (formid > -1) {
  582:         var domid = getIndexByName(formid,udom);
  583:         if (domid > -1) {
  584:             if (document.forms[formid].elements[domid].type == 'select-one') {
  585:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  586:             }
  587:             if (document.forms[formid].elements[domid].type == 'hidden') {
  588:                 userdom=document.forms[formid].elements[domid].value;
  589:             }
  590:         }
  591:     }
  592:     return userdom;
  593: }
  594: 
  595: ENDJS
  596: 
  597: }
  598: 
  599: sub userbrowser_javascript {
  600:     my $id_functions = &javascript_index_functions();
  601:     return <<"ENDUSERBRW";
  602: 
  603: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  604:     var url = '/adm/pickuser?';
  605:     var userdom = getDomainFromSelectbox(formname,udom);
  606:     if (userdom != null) {
  607:        if (userdom != '') {
  608:            url += 'srchdom='+userdom+'&';
  609:        }
  610:     }
  611:     url += 'form=' + formname + '&unameelement='+uname+
  612:                                 '&udomelement='+udom+
  613:                                 '&ulastelement='+ulast+
  614:                                 '&ufirstelement='+ufirst+
  615:                                 '&uemailelement='+uemail+
  616:                                 '&hideudomelement='+hideudom+
  617:                                 '&coursedom='+crsdom;
  618:     if ((caller != null) && (caller != undefined)) {
  619:         url += '&caller='+caller;
  620:     }
  621:     var title = 'User_Browser';
  622:     var options = 'scrollbars=1,resizable=1,menubar=0';
  623:     options += ',width=700,height=600';
  624:     var stdeditbrowser = open(url,title,options,'1');
  625:     stdeditbrowser.focus();
  626: }
  627: 
  628: function fix_domain (formname,udom,origdom,uname) {
  629:     var formid = getFormIdByName(formname);
  630:     if (formid > -1) {
  631:         var unameid = getIndexByName(formid,uname);
  632:         var domid = getIndexByName(formid,udom);
  633:         var hidedomid = getIndexByName(formid,origdom);
  634:         if (hidedomid > -1) {
  635:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  636:             var unameval = document.forms[formid].elements[unameid].value;
  637:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  638:                 if (domid > -1) {
  639:                     var slct = document.forms[formid].elements[domid];
  640:                     if (slct.type == 'select-one') {
  641:                         var i;
  642:                         for (i=0;i<slct.length;i++) {
  643:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  644:                         }
  645:                     }
  646:                     if (slct.type == 'hidden') {
  647:                         slct.value = fixeddom;
  648:                     }
  649:                 }
  650:             }
  651:         }
  652:     }
  653:     return;
  654: }
  655: 
  656: $id_functions
  657: ENDUSERBRW
  658: }
  659: 
  660: sub setsec_javascript {
  661:     my ($sec_element,$formname,$role_element) = @_;
  662:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  663:         $communityrolestr);
  664:     if ($role_element ne '') {
  665:         my @allroles = ('st','ta','ep','in','ad');
  666:         foreach my $crstype ('Course','Community') {
  667:             if ($crstype eq 'Community') {
  668:                 foreach my $role (@allroles) {
  669:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  670:                 }
  671:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  672:             } else {
  673:                 foreach my $role (@allroles) {
  674:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  675:                 }
  676:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  677:             }
  678:         }
  679:         $rolestr = '"'.join('","',@allroles).'"';
  680:         $courserolestr = '"'.join('","',@courserolenames).'"';
  681:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  682:     }
  683:     my $setsections = qq|
  684: function setSect(sectionlist) {
  685:     var sectionsArray = new Array();
  686:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  687:         sectionsArray = sectionlist.split(",");
  688:     }
  689:     var numSections = sectionsArray.length;
  690:     document.$formname.$sec_element.length = 0;
  691:     if (numSections == 0) {
  692:         document.$formname.$sec_element.multiple=false;
  693:         document.$formname.$sec_element.size=1;
  694:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  695:     } else {
  696:         if (numSections == 1) {
  697:             document.$formname.$sec_element.multiple=false;
  698:             document.$formname.$sec_element.size=1;
  699:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  700:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  701:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  702:         } else {
  703:             for (var i=0; i<numSections; i++) {
  704:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  705:             }
  706:             document.$formname.$sec_element.multiple=true
  707:             if (numSections < 3) {
  708:                 document.$formname.$sec_element.size=numSections;
  709:             } else {
  710:                 document.$formname.$sec_element.size=3;
  711:             }
  712:             document.$formname.$sec_element.options[0].selected = false
  713:         }
  714:     }
  715: }
  716: 
  717: function setRole(crstype) {
  718: |;
  719:     if ($role_element eq '') {
  720:         $setsections .= '    return;
  721: }
  722: ';
  723:     } else {
  724:         $setsections .= qq|
  725:     var elementLength = document.$formname.$role_element.length;
  726:     var allroles = Array($rolestr);
  727:     var courserolenames = Array($courserolestr);
  728:     var communityrolenames = Array($communityrolestr);
  729:     if (elementLength != undefined) {
  730:         if (document.$formname.$role_element.options[5].value == 'cc') {
  731:             if (crstype == 'Course') {
  732:                 return;
  733:             } else {
  734:                 allroles[5] = 'co';
  735:                 for (var i=0; i<6; i++) {
  736:                     document.$formname.$role_element.options[i].value = allroles[i];
  737:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  738:                 }
  739:             }
  740:         } else {
  741:             if (crstype == 'Community') {
  742:                 return;
  743:             } else {
  744:                 allroles[5] = 'cc';
  745:                 for (var i=0; i<6; i++) {
  746:                     document.$formname.$role_element.options[i].value = allroles[i];
  747:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  748:                 }
  749:             }
  750:         }
  751:     }
  752:     return;
  753: }
  754: |;
  755:     }
  756:     return $setsections;
  757: }
  758: 
  759: sub selectcourse_link {
  760:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  761:        $typeelement) = @_;
  762:    my $type = $selecttype;
  763:    my $linktext = &mt('Select Course');
  764:    if ($selecttype eq 'Community') {
  765:        $linktext = &mt('Select Community');
  766:    } elsif ($selecttype eq 'Course/Community') {
  767:        $linktext = &mt('Select Course/Community');
  768:        $type = '';
  769:    }
  770:    return '<span class="LC_nobreak">'
  771:          ."<a href='"
  772:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  773:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  774:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  775:          ."'>".$linktext.'</a>'
  776:          .'</span>';
  777: }
  778: 
  779: sub selectauthor_link {
  780:    my ($form,$udom)=@_;
  781:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  782:           &mt('Select Author').'</a>';
  783: }
  784: 
  785: sub selectuser_link {
  786:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  787:         $coursedom,$linktext,$caller) = @_;
  788:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  789:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  790:            ');">'.$linktext.'</a>';
  791: }
  792: 
  793: sub check_uncheck_jscript {
  794:     my $jscript = <<"ENDSCRT";
  795: function checkAll(field) {
  796:     if (field.length > 0) {
  797:         for (i = 0; i < field.length; i++) {
  798:             field[i].checked = true ;
  799:         }
  800:     } else {
  801:         field.checked = true
  802:     }
  803: }
  804:  
  805: function uncheckAll(field) {
  806:     if (field.length > 0) {
  807:         for (i = 0; i < field.length; i++) {
  808:             field[i].checked = false ;
  809:         }
  810:     } else {
  811:         field.checked = false ;
  812:     }
  813: }
  814: ENDSCRT
  815:     return $jscript;
  816: }
  817: 
  818: sub select_timezone {
  819:    my ($name,$selected,$onchange,$includeempty)=@_;
  820:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  821:    if ($includeempty) {
  822:        $output .= '<option value=""';
  823:        if (($selected eq '') || ($selected eq 'local')) {
  824:            $output .= ' selected="selected" ';
  825:        }
  826:        $output .= '> </option>';
  827:    }
  828:    my @timezones = DateTime::TimeZone->all_names;
  829:    foreach my $tzone (@timezones) {
  830:        $output.= '<option value="'.$tzone.'"';
  831:        if ($tzone eq $selected) {
  832:            $output.=' selected="selected"';
  833:        }
  834:        $output.=">$tzone</option>\n";
  835:    }
  836:    $output.="</select>";
  837:    return $output;
  838: }
  839: 
  840: sub select_datelocale {
  841:     my ($name,$selected,$onchange,$includeempty)=@_;
  842:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  843:     if ($includeempty) {
  844:         $output .= '<option value=""';
  845:         if ($selected eq '') {
  846:             $output .= ' selected="selected" ';
  847:         }
  848:         $output .= '> </option>';
  849:     }
  850:     my (@possibles,%locale_names);
  851:     my @locales = DateTime::Locale::Catalog::Locales;
  852:     foreach my $locale (@locales) {
  853:         if (ref($locale) eq 'HASH') {
  854:             my $id = $locale->{'id'};
  855:             if ($id ne '') {
  856:                 my $en_terr = $locale->{'en_territory'};
  857:                 my $native_terr = $locale->{'native_territory'};
  858:                 my @languages = &Apache::lonlocal::preferred_languages();
  859:                 if (grep(/^en$/,@languages) || !@languages) {
  860:                     if ($en_terr ne '') {
  861:                         $locale_names{$id} = '('.$en_terr.')';
  862:                     } elsif ($native_terr ne '') {
  863:                         $locale_names{$id} = $native_terr;
  864:                     }
  865:                 } else {
  866:                     if ($native_terr ne '') {
  867:                         $locale_names{$id} = $native_terr.' ';
  868:                     } elsif ($en_terr ne '') {
  869:                         $locale_names{$id} = '('.$en_terr.')';
  870:                     }
  871:                 }
  872:                 push (@possibles,$id);
  873:             }
  874:         }
  875:     }
  876:     foreach my $item (sort(@possibles)) {
  877:         $output.= '<option value="'.$item.'"';
  878:         if ($item eq $selected) {
  879:             $output.=' selected="selected"';
  880:         }
  881:         $output.=">$item";
  882:         if ($locale_names{$item} ne '') {
  883:             $output.="  $locale_names{$item}</option>\n";
  884:         }
  885:         $output.="</option>\n";
  886:     }
  887:     $output.="</select>";
  888:     return $output;
  889: }
  890: 
  891: sub select_language {
  892:     my ($name,$selected,$includeempty) = @_;
  893:     my %langchoices;
  894:     if ($includeempty) {
  895:         %langchoices = ('' => 'No language preference');
  896:     }
  897:     foreach my $id (&languageids()) {
  898:         my $code = &supportedlanguagecode($id);
  899:         if ($code) {
  900:             $langchoices{$code} = &plainlanguagedescription($id);
  901:         }
  902:     }
  903:     return &select_form($selected,$name,\%langchoices);
  904: }
  905: 
  906: =pod
  907: 
  908: =item * &linked_select_forms(...)
  909: 
  910: linked_select_forms returns a string containing a <script></script> block
  911: and html for two <select> menus.  The select menus will be linked in that
  912: changing the value of the first menu will result in new values being placed
  913: in the second menu.  The values in the select menu will appear in alphabetical
  914: order unless a defined order is provided.
  915: 
  916: linked_select_forms takes the following ordered inputs:
  917: 
  918: =over 4
  919: 
  920: =item * $formname, the name of the <form> tag
  921: 
  922: =item * $middletext, the text which appears between the <select> tags
  923: 
  924: =item * $firstdefault, the default value for the first menu
  925: 
  926: =item * $firstselectname, the name of the first <select> tag
  927: 
  928: =item * $secondselectname, the name of the second <select> tag
  929: 
  930: =item * $hashref, a reference to a hash containing the data for the menus.
  931: 
  932: =item * $menuorder, the order of values in the first menu
  933: 
  934: =back 
  935: 
  936: Below is an example of such a hash.  Only the 'text', 'default', and 
  937: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  938: values for the first select menu.  The text that coincides with the 
  939: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  940: and text for the second menu are given in the hash pointed to by 
  941: $menu{$choice1}->{'select2'}.  
  942: 
  943:  my %menu = ( A1 => { text =>"Choice A1" ,
  944:                        default => "B3",
  945:                        select2 => { 
  946:                            B1 => "Choice B1",
  947:                            B2 => "Choice B2",
  948:                            B3 => "Choice B3",
  949:                            B4 => "Choice B4"
  950:                            },
  951:                        order => ['B4','B3','B1','B2'],
  952:                    },
  953:                A2 => { text =>"Choice A2" ,
  954:                        default => "C2",
  955:                        select2 => { 
  956:                            C1 => "Choice C1",
  957:                            C2 => "Choice C2",
  958:                            C3 => "Choice C3"
  959:                            },
  960:                        order => ['C2','C1','C3'],
  961:                    },
  962:                A3 => { text =>"Choice A3" ,
  963:                        default => "D6",
  964:                        select2 => { 
  965:                            D1 => "Choice D1",
  966:                            D2 => "Choice D2",
  967:                            D3 => "Choice D3",
  968:                            D4 => "Choice D4",
  969:                            D5 => "Choice D5",
  970:                            D6 => "Choice D6",
  971:                            D7 => "Choice D7"
  972:                            },
  973:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  974:                    }
  975:                );
  976: 
  977: =cut
  978: 
  979: sub linked_select_forms {
  980:     my ($formname,
  981:         $middletext,
  982:         $firstdefault,
  983:         $firstselectname,
  984:         $secondselectname, 
  985:         $hashref,
  986:         $menuorder,
  987:         ) = @_;
  988:     my $second = "document.$formname.$secondselectname";
  989:     my $first = "document.$formname.$firstselectname";
  990:     # output the javascript to do the changing
  991:     my $result = '';
  992:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  993:     $result.="// <![CDATA[\n";
  994:     $result.="var select2data = new Object();\n";
  995:     $" = '","';
  996:     my $debug = '';
  997:     foreach my $s1 (sort(keys(%$hashref))) {
  998:         $result.="select2data.d_$s1 = new Object();\n";        
  999:         $result.="select2data.d_$s1.def = new String('".
 1000:             $hashref->{$s1}->{'default'}."');\n";
 1001:         $result.="select2data.d_$s1.values = new Array(";
 1002:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1003:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1004:             @s2values = @{$hashref->{$s1}->{'order'}};
 1005:         }
 1006:         $result.="\"@s2values\");\n";
 1007:         $result.="select2data.d_$s1.texts = new Array(";        
 1008:         my @s2texts;
 1009:         foreach my $value (@s2values) {
 1010:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1011:         }
 1012:         $result.="\"@s2texts\");\n";
 1013:     }
 1014:     $"=' ';
 1015:     $result.= <<"END";
 1016: 
 1017: function select1_changed() {
 1018:     // Determine new choice
 1019:     var newvalue = "d_" + $first.value;
 1020:     // update select2
 1021:     var values     = select2data[newvalue].values;
 1022:     var texts      = select2data[newvalue].texts;
 1023:     var select2def = select2data[newvalue].def;
 1024:     var i;
 1025:     // out with the old
 1026:     for (i = 0; i < $second.options.length; i++) {
 1027:         $second.options[i] = null;
 1028:     }
 1029:     // in with the nuclear
 1030:     for (i=0;i<values.length; i++) {
 1031:         $second.options[i] = new Option(values[i]);
 1032:         $second.options[i].value = values[i];
 1033:         $second.options[i].text = texts[i];
 1034:         if (values[i] == select2def) {
 1035:             $second.options[i].selected = true;
 1036:         }
 1037:     }
 1038: }
 1039: // ]]>
 1040: </script>
 1041: END
 1042:     # output the initial values for the selection lists
 1043:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1044:     my @order = sort(keys(%{$hashref}));
 1045:     if (ref($menuorder) eq 'ARRAY') {
 1046:         @order = @{$menuorder};
 1047:     }
 1048:     foreach my $value (@order) {
 1049:         $result.="    <option value=\"$value\" ";
 1050:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1051:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1052:     }
 1053:     $result .= "</select>\n";
 1054:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1055:     $result .= $middletext;
 1056:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1057:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1058:     
 1059:     my @secondorder = sort(keys(%select2));
 1060:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1061:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1062:     }
 1063:     foreach my $value (@secondorder) {
 1064:         $result.="    <option value=\"$value\" ";        
 1065:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1066:         $result.=">".&mt($select2{$value})."</option>\n";
 1067:     }
 1068:     $result .= "</select>\n";
 1069:     #    return $debug;
 1070:     return $result;
 1071: }   #  end of sub linked_select_forms {
 1072: 
 1073: =pod
 1074: 
 1075: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1076: 
 1077: Returns a string corresponding to an HTML link to the given help
 1078: $topic, where $topic corresponds to the name of a .tex file in
 1079: /home/httpd/html/adm/help/tex, with underscores replaced by
 1080: spaces. 
 1081: 
 1082: $text will optionally be linked to the same topic, allowing you to
 1083: link text in addition to the graphic. If you do not want to link
 1084: text, but wish to specify one of the later parameters, pass an
 1085: empty string. 
 1086: 
 1087: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1088: the link will not open a new window. If false, the link will open
 1089: a new window using Javascript. (Default is false.) 
 1090: 
 1091: $width and $height are optional numerical parameters that will
 1092: override the width and height of the popped up window, which may
 1093: be useful for certain help topics with big pictures included. 
 1094: 
 1095: =cut
 1096: 
 1097: sub help_open_topic {
 1098:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1099:     $text = "" if (not defined $text);
 1100:     $stayOnPage = 0 if (not defined $stayOnPage);
 1101:     $width = 350 if (not defined $width);
 1102:     $height = 400 if (not defined $height);
 1103:     my $filename = $topic;
 1104:     $filename =~ s/ /_/g;
 1105: 
 1106:     my $template = "";
 1107:     my $link;
 1108:     
 1109:     $topic=~s/\W/\_/g;
 1110: 
 1111:     if (!$stayOnPage) {
 1112: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1113:     } else {
 1114: 	$link = "/adm/help/${filename}.hlp";
 1115:     }
 1116: 
 1117:     # Add the text
 1118:     if ($text ne "") {	
 1119: 	$template.='<span class="LC_help_open_topic">'
 1120:                   .'<a target="_top" href="'.$link.'">'
 1121:                   .$text.'</a>';
 1122:     }
 1123: 
 1124:     # (Always) Add the graphic
 1125:     my $title = &mt('Online Help');
 1126:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1127:     if ($imgid ne '') {
 1128:         $imgid = ' id="'.$imgid.'"';
 1129:     }
 1130:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1131:               .'<img src="'.$helpicon.'" border="0"'
 1132:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1133:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
 1134:               .' /></a>';
 1135:     if ($text ne "") {
 1136:         $template.='</span>';
 1137:     }
 1138:     return $template;
 1139: 
 1140: }
 1141: 
 1142: # This is a quicky function for Latex cheatsheet editing, since it 
 1143: # appears in at least four places
 1144: sub helpLatexCheatsheet {
 1145:     my ($topic,$text,$not_author) = @_;
 1146:     my $out;
 1147:     my $addOther = '';
 1148:     if ($topic) {
 1149: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1150: 							       undef, undef, 600).
 1151: 								   '</span> ';
 1152:     }
 1153:     $out = '<span>' # Start cheatsheet
 1154: 	  .$addOther
 1155:           .'<span>'
 1156: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1157: 					       undef,undef,600)
 1158: 	  .'</span> <span>'
 1159: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1160: 					       undef,undef,600)
 1161: 	  .'</span>';
 1162:     unless ($not_author) {
 1163:         $out .= ' <span>'
 1164: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1165: 	                                            undef,undef,600)
 1166: 	       .'</span>';
 1167:     }
 1168:     $out .= '</span>'; # End cheatsheet
 1169:     return $out;
 1170: }
 1171: 
 1172: sub general_help {
 1173:     my $helptopic='Student_Intro';
 1174:     if ($env{'request.role'}=~/^(ca|au)/) {
 1175: 	$helptopic='Authoring_Intro';
 1176:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1177: 	$helptopic='Course_Coordination_Intro';
 1178:     } elsif ($env{'request.role'}=~/^dc/) {
 1179:         $helptopic='Domain_Coordination_Intro';
 1180:     }
 1181:     return $helptopic;
 1182: }
 1183: 
 1184: sub update_help_link {
 1185:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1186:     my $origurl = $ENV{'REQUEST_URI'};
 1187:     $origurl=~s|^/~|/priv/|;
 1188:     my $timestamp = time;
 1189:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1190:         $$datum = &escape($$datum);
 1191:     }
 1192: 
 1193:     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";
 1194:     my $output .= <<"ENDOUTPUT";
 1195: <script type="text/javascript">
 1196: // <![CDATA[
 1197: banner_link = '$banner_link';
 1198: // ]]>
 1199: </script>
 1200: ENDOUTPUT
 1201:     return $output;
 1202: }
 1203: 
 1204: # now just updates the help link and generates a blue icon
 1205: sub help_open_menu {
 1206:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1207: 	= @_;    
 1208:     $stayOnPage = 0 if (not defined $stayOnPage);
 1209:     # only use pop-up help (stayOnPage == 0)
 1210:     # if environment.remote is on (using remote control UI)
 1211:     if ($env{'environment.remote'} eq 'off' ) {
 1212:         $stayOnPage=1;
 1213:     }
 1214:     my $output;
 1215:     if ($component_help) {
 1216: 	if (!$text) {
 1217: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1218: 				       $width,$height);
 1219: 	} else {
 1220: 	    my $help_text;
 1221: 	    $help_text=&unescape($topic);
 1222: 	    $output='<table><tr><td>'.
 1223: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1224: 				 $width,$height).'</td></tr></table>';
 1225: 	}
 1226:     }
 1227:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1228:     return $output.$banner_link;
 1229: }
 1230: 
 1231: sub top_nav_help {
 1232:     my ($text) = @_;
 1233:     $text = &mt($text);
 1234:     my $stay_on_page = 
 1235: 	($env{'environment.remote'} eq 'off' );
 1236:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1237: 	                     : "javascript:helpMenu('open')";
 1238:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1239: 
 1240:     my $title = &mt('Get help');
 1241: 
 1242:     return <<"END";
 1243: $banner_link
 1244:  <a href="$link" title="$title">$text</a>
 1245: END
 1246: }
 1247: 
 1248: sub help_menu_js {
 1249:     my ($text) = @_;
 1250: 
 1251:     my $stayOnPage = 
 1252: 	($env{'environment.remote'} eq 'off' );
 1253: 
 1254:     my $width = 620;
 1255:     my $height = 600;
 1256:     my $helptopic=&general_help();
 1257:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1258:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1259:     my $start_page =
 1260:         &Apache::loncommon::start_page('Help Menu', undef,
 1261: 				       {'frameset'    => 1,
 1262: 					'js_ready'    => 1,
 1263: 					'add_entries' => {
 1264: 					    'border' => '0',
 1265: 					    'rows'   => "110,*",},});
 1266:     my $end_page =
 1267:         &Apache::loncommon::end_page({'frameset' => 1,
 1268: 				      'js_ready' => 1,});
 1269: 
 1270:     my $template .= <<"ENDTEMPLATE";
 1271: <script type="text/javascript">
 1272: // <![CDATA[
 1273: // <!-- BEGIN LON-CAPA Internal
 1274: var banner_link = '';
 1275: function helpMenu(target) {
 1276:     var caller = this;
 1277:     if (target == 'open') {
 1278:         var newWindow = null;
 1279:         try {
 1280:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1281:         }
 1282:         catch(error) {
 1283:             writeHelp(caller);
 1284:             return;
 1285:         }
 1286:         if (newWindow) {
 1287:             caller = newWindow;
 1288:         }
 1289:     }
 1290:     writeHelp(caller);
 1291:     return;
 1292: }
 1293: function writeHelp(caller) {
 1294:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1295:     caller.document.close()
 1296:     caller.focus()
 1297: }
 1298: // END LON-CAPA Internal -->
 1299: // ]]>
 1300: </script>
 1301: ENDTEMPLATE
 1302:     return $template;
 1303: }
 1304: 
 1305: sub help_open_bug {
 1306:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1307:     unless ($env{'user.adv'}) { return ''; }
 1308:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1309:     $text = "" if (not defined $text);
 1310:     $stayOnPage = 0 if (not defined $stayOnPage);
 1311:     if ($env{'environment.remote'} eq 'off' ) {
 1312: 	$stayOnPage=1;
 1313:     }
 1314:     $width = 600 if (not defined $width);
 1315:     $height = 600 if (not defined $height);
 1316: 
 1317:     $topic=~s/\W+/\+/g;
 1318:     my $link='';
 1319:     my $template='';
 1320:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1321: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1322:     if (!$stayOnPage)
 1323:     {
 1324: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1325:     }
 1326:     else
 1327:     {
 1328: 	$link = $url;
 1329:     }
 1330:     # Add the text
 1331:     if ($text ne "")
 1332:     {
 1333: 	$template .= 
 1334:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1335:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1336:     }
 1337: 
 1338:     # Add the graphic
 1339:     my $title = &mt('Report a Bug');
 1340:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1341:     $template .= <<"ENDTEMPLATE";
 1342:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1343: ENDTEMPLATE
 1344:     if ($text ne '') { $template.='</td></tr></table>' };
 1345:     return $template;
 1346: 
 1347: }
 1348: 
 1349: sub help_open_faq {
 1350:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1351:     unless ($env{'user.adv'}) { return ''; }
 1352:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1353:     $text = "" if (not defined $text);
 1354:     $stayOnPage = 0 if (not defined $stayOnPage);
 1355:     if ($env{'environment.remote'} eq 'off' ) {
 1356: 	$stayOnPage=1;
 1357:     }
 1358:     $width = 350 if (not defined $width);
 1359:     $height = 400 if (not defined $height);
 1360: 
 1361:     $topic=~s/\W+/\+/g;
 1362:     my $link='';
 1363:     my $template='';
 1364:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1365:     if (!$stayOnPage)
 1366:     {
 1367: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1368:     }
 1369:     else
 1370:     {
 1371: 	$link = $url;
 1372:     }
 1373: 
 1374:     # Add the text
 1375:     if ($text ne "")
 1376:     {
 1377: 	$template .= 
 1378:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1379:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1380:     }
 1381: 
 1382:     # Add the graphic
 1383:     my $title = &mt('View the FAQ');
 1384:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1385:     $template .= <<"ENDTEMPLATE";
 1386:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1387: ENDTEMPLATE
 1388:     if ($text ne '') { $template.='</td></tr></table>' };
 1389:     return $template;
 1390: 
 1391: }
 1392: 
 1393: ###############################################################
 1394: ###############################################################
 1395: 
 1396: =pod
 1397: 
 1398: =item * &change_content_javascript():
 1399: 
 1400: This and the next function allow you to create small sections of an
 1401: otherwise static HTML page that you can update on the fly with
 1402: Javascript, even in Netscape 4.
 1403: 
 1404: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1405: must be written to the HTML page once. It will prove the Javascript
 1406: function "change(name, content)". Calling the change function with the
 1407: name of the section 
 1408: you want to update, matching the name passed to C<changable_area>, and
 1409: the new content you want to put in there, will put the content into
 1410: that area.
 1411: 
 1412: B<Note>: Netscape 4 only reserves enough space for the changable area
 1413: to contain room for the original contents. You need to "make space"
 1414: for whatever changes you wish to make, and be B<sure> to check your
 1415: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1416: it's adequate for updating a one-line status display, but little more.
 1417: This script will set the space to 100% width, so you only need to
 1418: worry about height in Netscape 4.
 1419: 
 1420: Modern browsers are much less limiting, and if you can commit to the
 1421: user not using Netscape 4, this feature may be used freely with
 1422: pretty much any HTML.
 1423: 
 1424: =cut
 1425: 
 1426: sub change_content_javascript {
 1427:     # If we're on Netscape 4, we need to use Layer-based code
 1428:     if ($env{'browser.type'} eq 'netscape' &&
 1429: 	$env{'browser.version'} =~ /^4\./) {
 1430: 	return (<<NETSCAPE4);
 1431: 	function change(name, content) {
 1432: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1433: 	    doc.open();
 1434: 	    doc.write(content);
 1435: 	    doc.close();
 1436: 	}
 1437: NETSCAPE4
 1438:     } else {
 1439: 	# Otherwise, we need to use semi-standards-compliant code
 1440: 	# (technically, "innerHTML" isn't standard but the equivalent
 1441: 	# is really scary, and every useful browser supports it
 1442: 	return (<<DOMBASED);
 1443: 	function change(name, content) {
 1444: 	    element = document.getElementById(name);
 1445: 	    element.innerHTML = content;
 1446: 	}
 1447: DOMBASED
 1448:     }
 1449: }
 1450: 
 1451: =pod
 1452: 
 1453: =item * &changable_area($name,$origContent):
 1454: 
 1455: This provides a "changable area" that can be modified on the fly via
 1456: the Javascript code provided in C<change_content_javascript>. $name is
 1457: the name you will use to reference the area later; do not repeat the
 1458: same name on a given HTML page more then once. $origContent is what
 1459: the area will originally contain, which can be left blank.
 1460: 
 1461: =cut
 1462: 
 1463: sub changable_area {
 1464:     my ($name, $origContent) = @_;
 1465: 
 1466:     if ($env{'browser.type'} eq 'netscape' &&
 1467: 	$env{'browser.version'} =~ /^4\./) {
 1468: 	# If this is netscape 4, we need to use the Layer tag
 1469: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1470:     } else {
 1471: 	return "<span id='$name'>$origContent</span>";
 1472:     }
 1473: }
 1474: 
 1475: =pod
 1476: 
 1477: =item * &viewport_geometry_js 
 1478: 
 1479: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1480: 
 1481: =cut
 1482: 
 1483: 
 1484: sub viewport_geometry_js { 
 1485:     return <<"GEOMETRY";
 1486: var Geometry = {};
 1487: function init_geometry() {
 1488:     if (Geometry.init) { return };
 1489:     Geometry.init=1;
 1490:     if (window.innerHeight) {
 1491:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1492:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1493:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1494:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1495:     }
 1496:     else if (document.documentElement && document.documentElement.clientHeight) {
 1497:         Geometry.getViewportHeight =
 1498:             function() { return document.documentElement.clientHeight; };
 1499:         Geometry.getViewportWidth =
 1500:             function() { return document.documentElement.clientWidth; };
 1501: 
 1502:         Geometry.getHorizontalScroll =
 1503:             function() { return document.documentElement.scrollLeft; };
 1504:         Geometry.getVerticalScroll =
 1505:             function() { return document.documentElement.scrollTop; };
 1506:     }
 1507:     else if (document.body.clientHeight) {
 1508:         Geometry.getViewportHeight =
 1509:             function() { return document.body.clientHeight; };
 1510:         Geometry.getViewportWidth =
 1511:             function() { return document.body.clientWidth; };
 1512:         Geometry.getHorizontalScroll =
 1513:             function() { return document.body.scrollLeft; };
 1514:         Geometry.getVerticalScroll =
 1515:             function() { return document.body.scrollTop; };
 1516:     }
 1517: }
 1518: 
 1519: GEOMETRY
 1520: }
 1521: 
 1522: =pod
 1523: 
 1524: =item * &viewport_size_js()
 1525: 
 1526: 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. 
 1527: 
 1528: =cut
 1529: 
 1530: sub viewport_size_js {
 1531:     my $geometry = &viewport_geometry_js();
 1532:     return <<"DIMS";
 1533: 
 1534: $geometry
 1535: 
 1536: function getViewportDims(width,height) {
 1537:     init_geometry();
 1538:     width.value = Geometry.getViewportWidth();
 1539:     height.value = Geometry.getViewportHeight();
 1540:     return;
 1541: }
 1542: 
 1543: DIMS
 1544: }
 1545: 
 1546: =pod
 1547: 
 1548: =item * &resize_textarea_js()
 1549: 
 1550: emits the needed javascript to resize a textarea to be as big as possible
 1551: 
 1552: creates a function resize_textrea that takes two IDs first should be
 1553: the id of the element to resize, second should be the id of a div that
 1554: surrounds everything that comes after the textarea, this routine needs
 1555: to be attached to the <body> for the onload and onresize events.
 1556: 
 1557: =back
 1558: 
 1559: =cut
 1560: 
 1561: sub resize_textarea_js {
 1562:     my $geometry = &viewport_geometry_js();
 1563:     return <<"RESIZE";
 1564:     <script type="text/javascript">
 1565: // <![CDATA[
 1566: $geometry
 1567: 
 1568: function getX(element) {
 1569:     var x = 0;
 1570:     while (element) {
 1571: 	x += element.offsetLeft;
 1572: 	element = element.offsetParent;
 1573:     }
 1574:     return x;
 1575: }
 1576: function getY(element) {
 1577:     var y = 0;
 1578:     while (element) {
 1579: 	y += element.offsetTop;
 1580: 	element = element.offsetParent;
 1581:     }
 1582:     return y;
 1583: }
 1584: 
 1585: 
 1586: function resize_textarea(textarea_id,bottom_id) {
 1587:     init_geometry();
 1588:     var textarea        = document.getElementById(textarea_id);
 1589:     //alert(textarea);
 1590: 
 1591:     var textarea_top    = getY(textarea);
 1592:     var textarea_height = textarea.offsetHeight;
 1593:     var bottom          = document.getElementById(bottom_id);
 1594:     var bottom_top      = getY(bottom);
 1595:     var bottom_height   = bottom.offsetHeight;
 1596:     var window_height   = Geometry.getViewportHeight();
 1597:     var fudge           = 23;
 1598:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1599:     if (new_height < 300) {
 1600: 	new_height = 300;
 1601:     }
 1602:     textarea.style.height=new_height+'px';
 1603: }
 1604: // ]]>
 1605: </script>
 1606: RESIZE
 1607: 
 1608: }
 1609: 
 1610: =pod
 1611: 
 1612: =head1 Excel and CSV file utility routines
 1613: 
 1614: =over 4
 1615: 
 1616: =cut
 1617: 
 1618: ###############################################################
 1619: ###############################################################
 1620: 
 1621: =pod
 1622: 
 1623: =item * &csv_translate($text) 
 1624: 
 1625: Translate $text to allow it to be output as a 'comma separated values' 
 1626: format.
 1627: 
 1628: =cut
 1629: 
 1630: ###############################################################
 1631: ###############################################################
 1632: sub csv_translate {
 1633:     my $text = shift;
 1634:     $text =~ s/\"/\"\"/g;
 1635:     $text =~ s/\n/ /g;
 1636:     return $text;
 1637: }
 1638: 
 1639: ###############################################################
 1640: ###############################################################
 1641: 
 1642: =pod
 1643: 
 1644: =item * &define_excel_formats()
 1645: 
 1646: Define some commonly used Excel cell formats.
 1647: 
 1648: Currently supported formats:
 1649: 
 1650: =over 4
 1651: 
 1652: =item header
 1653: 
 1654: =item bold
 1655: 
 1656: =item h1
 1657: 
 1658: =item h2
 1659: 
 1660: =item h3
 1661: 
 1662: =item h4
 1663: 
 1664: =item i
 1665: 
 1666: =item date
 1667: 
 1668: =back
 1669: 
 1670: Inputs: $workbook
 1671: 
 1672: Returns: $format, a hash reference.
 1673: 
 1674: =cut
 1675: 
 1676: ###############################################################
 1677: ###############################################################
 1678: sub define_excel_formats {
 1679:     my ($workbook) = @_;
 1680:     my $format;
 1681:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1682:                                                 bottom    => 1,
 1683:                                                 align     => 'center');
 1684:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1685:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1686:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1687:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1688:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1689:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1690:     $format->{'date'} = $workbook->add_format(num_format=>
 1691:                                             'mm/dd/yyyy hh:mm:ss');
 1692:     return $format;
 1693: }
 1694: 
 1695: ###############################################################
 1696: ###############################################################
 1697: 
 1698: =pod
 1699: 
 1700: =item * &create_workbook()
 1701: 
 1702: Create an Excel worksheet.  If it fails, output message on the
 1703: request object and return undefs.
 1704: 
 1705: Inputs: Apache request object
 1706: 
 1707: Returns (undef) on failure, 
 1708:     Excel worksheet object, scalar with filename, and formats 
 1709:     from &Apache::loncommon::define_excel_formats on success
 1710: 
 1711: =cut
 1712: 
 1713: ###############################################################
 1714: ###############################################################
 1715: sub create_workbook {
 1716:     my ($r) = @_;
 1717:         #
 1718:     # Create the excel spreadsheet
 1719:     my $filename = '/prtspool/'.
 1720:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1721:         time.'_'.rand(1000000000).'.xls';
 1722:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1723:     if (! defined($workbook)) {
 1724:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1725:         $r->print(
 1726:             '<p class="LC_error">'
 1727:            .&mt('Problems occurred in creating the new Excel file.')
 1728:            .' '.&mt('This error has been logged.')
 1729:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1730:            .'</p>'
 1731:         );
 1732:         return (undef);
 1733:     }
 1734:     #
 1735:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1736:     #
 1737:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1738:     return ($workbook,$filename,$format);
 1739: }
 1740: 
 1741: ###############################################################
 1742: ###############################################################
 1743: 
 1744: =pod
 1745: 
 1746: =item * &create_text_file()
 1747: 
 1748: Create a file to write to and eventually make available to the user.
 1749: If file creation fails, outputs an error message on the request object and 
 1750: return undefs.
 1751: 
 1752: Inputs: Apache request object, and file suffix
 1753: 
 1754: Returns (undef) on failure, 
 1755:     Filehandle and filename on success.
 1756: 
 1757: =cut
 1758: 
 1759: ###############################################################
 1760: ###############################################################
 1761: sub create_text_file {
 1762:     my ($r,$suffix) = @_;
 1763:     if (! defined($suffix)) { $suffix = 'txt'; };
 1764:     my $fh;
 1765:     my $filename = '/prtspool/'.
 1766:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1767:         time.'_'.rand(1000000000).'.'.$suffix;
 1768:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1769:     if (! defined($fh)) {
 1770:         $r->log_error("Couldn't open $filename for output $!");
 1771:         $r->print(
 1772:             '<p class="LC_error">'
 1773:            .&mt('Problems occurred in creating the output file.')
 1774:            .' '.&mt('This error has been logged.')
 1775:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1776:            .'</p>'
 1777:         );
 1778:     }
 1779:     return ($fh,$filename)
 1780: }
 1781: 
 1782: 
 1783: =pod 
 1784: 
 1785: =back
 1786: 
 1787: =cut
 1788: 
 1789: ###############################################################
 1790: ##        Home server <option> list generating code          ##
 1791: ###############################################################
 1792: 
 1793: # ------------------------------------------
 1794: 
 1795: sub domain_select {
 1796:     my ($name,$value,$multiple)=@_;
 1797:     my %domains=map { 
 1798: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1799:     } &Apache::lonnet::all_domains();
 1800:     if ($multiple) {
 1801: 	$domains{''}=&mt('Any domain');
 1802: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1803: 	return &multiple_select_form($name,$value,4,\%domains);
 1804:     } else {
 1805: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1806: 	return &select_form($name,$value,\%domains);
 1807:     }
 1808: }
 1809: 
 1810: #-------------------------------------------
 1811: 
 1812: =pod
 1813: 
 1814: =head1 Routines for form select boxes
 1815: 
 1816: =over 4
 1817: 
 1818: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1819: 
 1820: Returns a string containing a <select> element int multiple mode
 1821: 
 1822: 
 1823: Args:
 1824:   $name - name of the <select> element
 1825:   $value - scalar or array ref of values that should already be selected
 1826:   $size - number of rows long the select element is
 1827:   $hash - the elements should be 'option' => 'shown text'
 1828:           (shown text should already have been &mt())
 1829:   $order - (optional) array ref of the order to show the elements in
 1830: 
 1831: =cut
 1832: 
 1833: #-------------------------------------------
 1834: sub multiple_select_form {
 1835:     my ($name,$value,$size,$hash,$order)=@_;
 1836:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1837:     my $output='';
 1838:     if (! defined($size)) {
 1839:         $size = 4;
 1840:         if (scalar(keys(%$hash))<4) {
 1841:             $size = scalar(keys(%$hash));
 1842:         }
 1843:     }
 1844:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1845:     my @order;
 1846:     if (ref($order) eq 'ARRAY')  {
 1847:         @order = @{$order};
 1848:     } else {
 1849:         @order = sort(keys(%$hash));
 1850:     }
 1851:     if (exists($$hash{'select_form_order'})) {
 1852:         @order = @{$$hash{'select_form_order'}};
 1853:     }
 1854:         
 1855:     foreach my $key (@order) {
 1856:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1857:         $output.='selected="selected" ' if ($selected{$key});
 1858:         $output.='>'.$hash->{$key}."</option>\n";
 1859:     }
 1860:     $output.="</select>\n";
 1861:     return $output;
 1862: }
 1863: 
 1864: #-------------------------------------------
 1865: 
 1866: =pod
 1867: 
 1868: =item * &select_form($defdom,$name,$hashref,$onchange)
 1869: 
 1870: Returns a string containing a <select name='$name' size='1'> form to 
 1871: allow a user to select options from a ref to a hash containing:
 1872: option_name => displayed text. An optional $onchange can include
 1873: a javascript onchange item, e.g., onchange="this.form.submit();"
 1874: 
 1875: See lonrights.pm for an example invocation and use.
 1876: 
 1877: =cut
 1878: 
 1879: #-------------------------------------------
 1880: sub select_form {
 1881:     my ($def,$name,$hashref,$onchange) = @_;
 1882:     return unless (ref($hashref) eq 'HASH');
 1883:     if ($onchange) {
 1884:         $onchange = ' onchange="'.$onchange.'"';
 1885:     }
 1886:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1887:     my @keys;
 1888:     if (exists($hashref->{'select_form_order'})) {
 1889:         @keys=@{$hashref->{'select_form_order'}};
 1890:     } else {
 1891:         @keys=sort(keys(%{$hashref}));
 1892:     }
 1893:     foreach my $key (@keys) {
 1894:         $selectform.=
 1895: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1896:             ($key eq $def ? 'selected="selected" ' : '').
 1897:                 ">".$hashref->{$key}."</option>\n";
 1898:     }
 1899:     $selectform.="</select>";
 1900:     return $selectform;
 1901: }
 1902: 
 1903: # For display filters
 1904: 
 1905: sub display_filter {
 1906:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1907:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1908:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1909: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1910: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1911: 	   '</label></span> <span class="LC_nobreak">'.
 1912:            &mt('Filter [_1]',
 1913: 	   &select_form($env{'form.displayfilter'},
 1914: 			'displayfilter',
 1915: 			{'currentfolder' => 'Current folder/page',
 1916: 			 'containing' => 'Containing phrase',
 1917: 			 'none' => 'None'})).
 1918: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1919: }
 1920: 
 1921: sub gradeleveldescription {
 1922:     my $gradelevel=shift;
 1923:     my %gradelevels=(0 => 'Not specified',
 1924: 		     1 => 'Grade 1',
 1925: 		     2 => 'Grade 2',
 1926: 		     3 => 'Grade 3',
 1927: 		     4 => 'Grade 4',
 1928: 		     5 => 'Grade 5',
 1929: 		     6 => 'Grade 6',
 1930: 		     7 => 'Grade 7',
 1931: 		     8 => 'Grade 8',
 1932: 		     9 => 'Grade 9',
 1933: 		     10 => 'Grade 10',
 1934: 		     11 => 'Grade 11',
 1935: 		     12 => 'Grade 12',
 1936: 		     13 => 'Grade 13',
 1937: 		     14 => '100 Level',
 1938: 		     15 => '200 Level',
 1939: 		     16 => '300 Level',
 1940: 		     17 => '400 Level',
 1941: 		     18 => 'Graduate Level');
 1942:     return &mt($gradelevels{$gradelevel});
 1943: }
 1944: 
 1945: sub select_level_form {
 1946:     my ($deflevel,$name)=@_;
 1947:     unless ($deflevel) { $deflevel=0; }
 1948:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1949:     for (my $i=0; $i<=18; $i++) {
 1950:         $selectform.="<option value=\"$i\" ".
 1951:             ($i==$deflevel ? 'selected="selected" ' : '').
 1952:                 ">".&gradeleveldescription($i)."</option>\n";
 1953:     }
 1954:     $selectform.="</select>";
 1955:     return $selectform;
 1956: }
 1957: 
 1958: #-------------------------------------------
 1959: 
 1960: =pod
 1961: 
 1962: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 1963: 
 1964: Returns a string containing a <select name='$name' size='1'> form to 
 1965: allow a user to select the domain to preform an operation in.  
 1966: See loncreateuser.pm for an example invocation and use.
 1967: 
 1968: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1969: selected");
 1970: 
 1971: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1972: 
 1973: 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.
 1974: 
 1975: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 1976: 
 1977: =cut
 1978: 
 1979: #-------------------------------------------
 1980: sub select_dom_form {
 1981:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 1982:     if ($onchange) {
 1983:         $onchange = ' onchange="'.$onchange.'"';
 1984:     }
 1985:     my @domains;
 1986:     if (ref($incdoms) eq 'ARRAY') {
 1987:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 1988:     } else {
 1989:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1990:     }
 1991:     if ($includeempty) { @domains=('',@domains); }
 1992:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1993:     foreach my $dom (@domains) {
 1994:         $selectdomain.="<option value=\"$dom\" ".
 1995:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1996:         if ($showdomdesc) {
 1997:             if ($dom ne '') {
 1998:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1999:                 if ($domdesc ne '') {
 2000:                     $selectdomain .= ' ('.$domdesc.')';
 2001:                 }
 2002:             } 
 2003:         }
 2004:         $selectdomain .= "</option>\n";
 2005:     }
 2006:     $selectdomain.="</select>";
 2007:     return $selectdomain;
 2008: }
 2009: 
 2010: #-------------------------------------------
 2011: 
 2012: =pod
 2013: 
 2014: =item * &home_server_form_item($domain,$name,$defaultflag)
 2015: 
 2016: input: 4 arguments (two required, two optional) - 
 2017:     $domain - domain of new user
 2018:     $name - name of form element
 2019:     $default - Value of 'default' causes a default item to be first 
 2020:                             option, and selected by default. 
 2021:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2022:                             if 1 server found, or default, if 0 found.
 2023: output: returns 2 items: 
 2024: (a) form element which contains either:
 2025:    (i) <select name="$name">
 2026:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2027:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2028:        </select>
 2029:        form item if there are multiple library servers in $domain, or
 2030:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2031:        if there is only one library server in $domain.
 2032: 
 2033: (b) number of library servers found.
 2034: 
 2035: See loncreateuser.pm for example of use.
 2036: 
 2037: =cut
 2038: 
 2039: #-------------------------------------------
 2040: sub home_server_form_item {
 2041:     my ($domain,$name,$default,$hide) = @_;
 2042:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2043:     my $result;
 2044:     my $numlib = keys(%servers);
 2045:     if ($numlib > 1) {
 2046:         $result .= '<select name="'.$name.'" />'."\n";
 2047:         if ($default) {
 2048:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2049:                        '</option>'."\n";
 2050:         }
 2051:         foreach my $hostid (sort(keys(%servers))) {
 2052:             $result.= '<option value="'.$hostid.'">'.
 2053: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2054:         }
 2055:         $result .= '</select>'."\n";
 2056:     } elsif ($numlib == 1) {
 2057:         my $hostid;
 2058:         foreach my $item (keys(%servers)) {
 2059:             $hostid = $item;
 2060:         }
 2061:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2062:                    $hostid.'" />';
 2063:                    if (!$hide) {
 2064:                        $result .= $hostid.' '.$servers{$hostid};
 2065:                    }
 2066:                    $result .= "\n";
 2067:     } elsif ($default) {
 2068:         $result .= '<input type="hidden" name="'.$name.
 2069:                    '" value="default" />';
 2070:                    if (!$hide) {
 2071:                        $result .= &mt('default');
 2072:                    }
 2073:                    $result .= "\n";
 2074:     }
 2075:     return ($result,$numlib);
 2076: }
 2077: 
 2078: =pod
 2079: 
 2080: =back 
 2081: 
 2082: =cut
 2083: 
 2084: ###############################################################
 2085: ##                  Decoding User Agent                      ##
 2086: ###############################################################
 2087: 
 2088: =pod
 2089: 
 2090: =head1 Decoding the User Agent
 2091: 
 2092: =over 4
 2093: 
 2094: =item * &decode_user_agent()
 2095: 
 2096: Inputs: $r
 2097: 
 2098: Outputs:
 2099: 
 2100: =over 4
 2101: 
 2102: =item * $httpbrowser
 2103: 
 2104: =item * $clientbrowser
 2105: 
 2106: =item * $clientversion
 2107: 
 2108: =item * $clientmathml
 2109: 
 2110: =item * $clientunicode
 2111: 
 2112: =item * $clientos
 2113: 
 2114: =back
 2115: 
 2116: =back 
 2117: 
 2118: =cut
 2119: 
 2120: ###############################################################
 2121: ###############################################################
 2122: sub decode_user_agent {
 2123:     my ($r)=@_;
 2124:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2125:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2126:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2127:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2128:     my $clientbrowser='unknown';
 2129:     my $clientversion='0';
 2130:     my $clientmathml='';
 2131:     my $clientunicode='0';
 2132:     for (my $i=0;$i<=$#browsertype;$i++) {
 2133:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2134: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2135: 	    $clientbrowser=$bname;
 2136:             $httpbrowser=~/$vreg/i;
 2137: 	    $clientversion=$1;
 2138:             $clientmathml=($clientversion>=$minv);
 2139:             $clientunicode=($clientversion>=$univ);
 2140: 	}
 2141:     }
 2142:     my $clientos='unknown';
 2143:     if (($httpbrowser=~/linux/i) ||
 2144:         ($httpbrowser=~/unix/i) ||
 2145:         ($httpbrowser=~/ux/i) ||
 2146:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2147:     if (($httpbrowser=~/vax/i) ||
 2148:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2149:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2150:     if (($httpbrowser=~/mac/i) ||
 2151:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2152:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2153:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2154:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2155:             $clientunicode,$clientos,);
 2156: }
 2157: 
 2158: ###############################################################
 2159: ##    Authentication changing form generation subroutines    ##
 2160: ###############################################################
 2161: ##
 2162: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2163: ## hash, and have reasonable default values.
 2164: ##
 2165: ##    formname = the name given in the <form> tag.
 2166: #-------------------------------------------
 2167: 
 2168: =pod
 2169: 
 2170: =head1 Authentication Routines
 2171: 
 2172: =over 4
 2173: 
 2174: =item * &authform_xxxxxx()
 2175: 
 2176: The authform_xxxxxx subroutines provide javascript and html forms which 
 2177: handle some of the conveniences required for authentication forms.  
 2178: This is not an optimal method, but it works.  
 2179: 
 2180: =over 4
 2181: 
 2182: =item * authform_header
 2183: 
 2184: =item * authform_authorwarning
 2185: 
 2186: =item * authform_nochange
 2187: 
 2188: =item * authform_kerberos
 2189: 
 2190: =item * authform_internal
 2191: 
 2192: =item * authform_filesystem
 2193: 
 2194: =back
 2195: 
 2196: See loncreateuser.pm for invocation and use examples.
 2197: 
 2198: =cut
 2199: 
 2200: #-------------------------------------------
 2201: sub authform_header{  
 2202:     my %in = (
 2203:         formname => 'cu',
 2204:         kerb_def_dom => '',
 2205:         @_,
 2206:     );
 2207:     $in{'formname'} = 'document.' . $in{'formname'};
 2208:     my $result='';
 2209: 
 2210: #---------------------------------------------- Code for upper case translation
 2211:     my $Javascript_toUpperCase;
 2212:     unless ($in{kerb_def_dom}) {
 2213:         $Javascript_toUpperCase =<<"END";
 2214:         switch (choice) {
 2215:            case 'krb': currentform.elements[choicearg].value =
 2216:                currentform.elements[choicearg].value.toUpperCase();
 2217:                break;
 2218:            default:
 2219:         }
 2220: END
 2221:     } else {
 2222:         $Javascript_toUpperCase = "";
 2223:     }
 2224: 
 2225:     my $radioval = "'nochange'";
 2226:     if (defined($in{'curr_authtype'})) {
 2227:         if ($in{'curr_authtype'} ne '') {
 2228:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2229:         }
 2230:     }
 2231:     my $argfield = 'null';
 2232:     if (defined($in{'mode'})) {
 2233:         if ($in{'mode'} eq 'modifycourse')  {
 2234:             if (defined($in{'curr_autharg'})) {
 2235:                 if ($in{'curr_autharg'} ne '') {
 2236:                     $argfield = "'$in{'curr_autharg'}'";
 2237:                 }
 2238:             }
 2239:         }
 2240:     }
 2241: 
 2242:     $result.=<<"END";
 2243: var current = new Object();
 2244: current.radiovalue = $radioval;
 2245: current.argfield = $argfield;
 2246: 
 2247: function changed_radio(choice,currentform) {
 2248:     var choicearg = choice + 'arg';
 2249:     // If a radio button in changed, we need to change the argfield
 2250:     if (current.radiovalue != choice) {
 2251:         current.radiovalue = choice;
 2252:         if (current.argfield != null) {
 2253:             currentform.elements[current.argfield].value = '';
 2254:         }
 2255:         if (choice == 'nochange') {
 2256:             current.argfield = null;
 2257:         } else {
 2258:             current.argfield = choicearg;
 2259:             switch(choice) {
 2260:                 case 'krb': 
 2261:                     currentform.elements[current.argfield].value = 
 2262:                         "$in{'kerb_def_dom'}";
 2263:                 break;
 2264:               default:
 2265:                 break;
 2266:             }
 2267:         }
 2268:     }
 2269:     return;
 2270: }
 2271: 
 2272: function changed_text(choice,currentform) {
 2273:     var choicearg = choice + 'arg';
 2274:     if (currentform.elements[choicearg].value !='') {
 2275:         $Javascript_toUpperCase
 2276:         // clear old field
 2277:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2278:             currentform.elements[current.argfield].value = '';
 2279:         }
 2280:         current.argfield = choicearg;
 2281:     }
 2282:     set_auth_radio_buttons(choice,currentform);
 2283:     return;
 2284: }
 2285: 
 2286: function set_auth_radio_buttons(newvalue,currentform) {
 2287:     var numauthchoices = currentform.login.length;
 2288:     if (typeof numauthchoices  == "undefined") {
 2289:         return;
 2290:     }
 2291:     var i=0;
 2292:     while (i < numauthchoices) {
 2293:         if (currentform.login[i].value == newvalue) { break; }
 2294:         i++;
 2295:     }
 2296:     if (i == numauthchoices) {
 2297:         return;
 2298:     }
 2299:     current.radiovalue = newvalue;
 2300:     currentform.login[i].checked = true;
 2301:     return;
 2302: }
 2303: END
 2304:     return $result;
 2305: }
 2306: 
 2307: sub authform_authorwarning{
 2308:     my $result='';
 2309:     $result='<i>'.
 2310:         &mt('As a general rule, only authors or co-authors should be '.
 2311:             'filesystem authenticated '.
 2312:             '(which allows access to the server filesystem).')."</i>\n";
 2313:     return $result;
 2314: }
 2315: 
 2316: sub authform_nochange{  
 2317:     my %in = (
 2318:               formname => 'document.cu',
 2319:               kerb_def_dom => 'MSU.EDU',
 2320:               @_,
 2321:           );
 2322:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2323:     my $result;
 2324:     if (keys(%can_assign) == 0) {
 2325:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2326:     } else {
 2327:         $result = '<label>'.&mt('[_1] Do not change login data',
 2328:                   '<input type="radio" name="login" value="nochange" '.
 2329:                   'checked="checked" onclick="'.
 2330:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2331: 	    '</label>';
 2332:     }
 2333:     return $result;
 2334: }
 2335: 
 2336: sub authform_kerberos {
 2337:     my %in = (
 2338:               formname => 'document.cu',
 2339:               kerb_def_dom => 'MSU.EDU',
 2340:               kerb_def_auth => 'krb4',
 2341:               @_,
 2342:               );
 2343:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2344:         $autharg,$jscall);
 2345:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2346:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2347:        $check5 = ' checked="checked"';
 2348:     } else {
 2349:        $check4 = ' checked="checked"';
 2350:     }
 2351:     $krbarg = $in{'kerb_def_dom'};
 2352:     if (defined($in{'curr_authtype'})) {
 2353:         if ($in{'curr_authtype'} eq 'krb') {
 2354:             $krbcheck = ' checked="checked"';
 2355:             if (defined($in{'mode'})) {
 2356:                 if ($in{'mode'} eq 'modifyuser') {
 2357:                     $krbcheck = '';
 2358:                 }
 2359:             }
 2360:             if (defined($in{'curr_kerb_ver'})) {
 2361:                 if ($in{'curr_krb_ver'} eq '5') {
 2362:                     $check5 = ' checked="checked"';
 2363:                     $check4 = '';
 2364:                 } else {
 2365:                     $check4 = ' checked="checked"';
 2366:                     $check5 = '';
 2367:                 }
 2368:             }
 2369:             if (defined($in{'curr_autharg'})) {
 2370:                 $krbarg = $in{'curr_autharg'};
 2371:             }
 2372:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2373:                 if (defined($in{'curr_autharg'})) {
 2374:                     $result = 
 2375:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2376:         $in{'curr_autharg'},$krbver);
 2377:                 } else {
 2378:                     $result =
 2379:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2380:                 }
 2381:                 return $result; 
 2382:             }
 2383:         }
 2384:     } else {
 2385:         if ($authnum == 1) {
 2386:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2387:         }
 2388:     }
 2389:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2390:         return;
 2391:     } elsif ($authtype eq '') {
 2392:         if (defined($in{'mode'})) {
 2393:             if ($in{'mode'} eq 'modifycourse') {
 2394:                 if ($authnum == 1) {
 2395:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2396:                 }
 2397:             }
 2398:         }
 2399:     }
 2400:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2401:     if ($authtype eq '') {
 2402:         $authtype = '<input type="radio" name="login" value="krb" '.
 2403:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2404:                     $krbcheck.' />';
 2405:     }
 2406:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2407:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2408:          $in{'curr_authtype'} eq 'krb5') ||
 2409:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2410:          $in{'curr_authtype'} eq 'krb4')) {
 2411:         $result .= &mt
 2412:         ('[_1] Kerberos authenticated with domain [_2] '.
 2413:          '[_3] Version 4 [_4] Version 5 [_5]',
 2414:          '<label>'.$authtype,
 2415:          '</label><input type="text" size="10" name="krbarg" '.
 2416:              'value="'.$krbarg.'" '.
 2417:              'onchange="'.$jscall.'" />',
 2418:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2419:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2420: 	 '</label>');
 2421:     } elsif ($can_assign{'krb4'}) {
 2422:         $result .= &mt
 2423:         ('[_1] Kerberos authenticated with domain [_2] '.
 2424:          '[_3] Version 4 [_4]',
 2425:          '<label>'.$authtype,
 2426:          '</label><input type="text" size="10" name="krbarg" '.
 2427:              'value="'.$krbarg.'" '.
 2428:              'onchange="'.$jscall.'" />',
 2429:          '<label><input type="hidden" name="krbver" value="4" />',
 2430:          '</label>');
 2431:     } elsif ($can_assign{'krb5'}) {
 2432:         $result .= &mt
 2433:         ('[_1] Kerberos authenticated with domain [_2] '.
 2434:          '[_3] Version 5 [_4]',
 2435:          '<label>'.$authtype,
 2436:          '</label><input type="text" size="10" name="krbarg" '.
 2437:              'value="'.$krbarg.'" '.
 2438:              'onchange="'.$jscall.'" />',
 2439:          '<label><input type="hidden" name="krbver" value="5" />',
 2440:          '</label>');
 2441:     }
 2442:     return $result;
 2443: }
 2444: 
 2445: sub authform_internal{  
 2446:     my %in = (
 2447:                 formname => 'document.cu',
 2448:                 kerb_def_dom => 'MSU.EDU',
 2449:                 @_,
 2450:                 );
 2451:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2452:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2453:     if (defined($in{'curr_authtype'})) {
 2454:         if ($in{'curr_authtype'} eq 'int') {
 2455:             if ($can_assign{'int'}) {
 2456:                 $intcheck = 'checked="checked" ';
 2457:                 if (defined($in{'mode'})) {
 2458:                     if ($in{'mode'} eq 'modifyuser') {
 2459:                         $intcheck = '';
 2460:                     }
 2461:                 }
 2462:                 if (defined($in{'curr_autharg'})) {
 2463:                     $intarg = $in{'curr_autharg'};
 2464:                 }
 2465:             } else {
 2466:                 $result = &mt('Currently internally authenticated.');
 2467:                 return $result;
 2468:             }
 2469:         }
 2470:     } else {
 2471:         if ($authnum == 1) {
 2472:             $authtype = '<input type="hidden" name="login" value="int" />';
 2473:         }
 2474:     }
 2475:     if (!$can_assign{'int'}) {
 2476:         return;
 2477:     } elsif ($authtype eq '') {
 2478:         if (defined($in{'mode'})) {
 2479:             if ($in{'mode'} eq 'modifycourse') {
 2480:                 if ($authnum == 1) {
 2481:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2482:                 }
 2483:             }
 2484:         }
 2485:     }
 2486:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2487:     if ($authtype eq '') {
 2488:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2489:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2490:     }
 2491:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2492:                $intarg.'" onchange="'.$jscall.'" />';
 2493:     $result = &mt
 2494:         ('[_1] Internally authenticated (with initial password [_2])',
 2495:          '<label>'.$authtype,'</label>'.$autharg);
 2496:     $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>';
 2497:     return $result;
 2498: }
 2499: 
 2500: sub authform_local{  
 2501:     my %in = (
 2502:               formname => 'document.cu',
 2503:               kerb_def_dom => 'MSU.EDU',
 2504:               @_,
 2505:               );
 2506:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2507:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2508:     if (defined($in{'curr_authtype'})) {
 2509:         if ($in{'curr_authtype'} eq 'loc') {
 2510:             if ($can_assign{'loc'}) {
 2511:                 $loccheck = 'checked="checked" ';
 2512:                 if (defined($in{'mode'})) {
 2513:                     if ($in{'mode'} eq 'modifyuser') {
 2514:                         $loccheck = '';
 2515:                     }
 2516:                 }
 2517:                 if (defined($in{'curr_autharg'})) {
 2518:                     $locarg = $in{'curr_autharg'};
 2519:                 }
 2520:             } else {
 2521:                 $result = &mt('Currently using local (institutional) authentication.');
 2522:                 return $result;
 2523:             }
 2524:         }
 2525:     } else {
 2526:         if ($authnum == 1) {
 2527:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2528:         }
 2529:     }
 2530:     if (!$can_assign{'loc'}) {
 2531:         return;
 2532:     } elsif ($authtype eq '') {
 2533:         if (defined($in{'mode'})) {
 2534:             if ($in{'mode'} eq 'modifycourse') {
 2535:                 if ($authnum == 1) {
 2536:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2537:                 }
 2538:             }
 2539:         }
 2540:     }
 2541:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2542:     if ($authtype eq '') {
 2543:         $authtype = '<input type="radio" name="login" value="loc" '.
 2544:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2545:                     $jscall.'" />';
 2546:     }
 2547:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2548:                $locarg.'" onchange="'.$jscall.'" />';
 2549:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2550:                   '<label>'.$authtype,'</label>'.$autharg);
 2551:     return $result;
 2552: }
 2553: 
 2554: sub authform_filesystem{  
 2555:     my %in = (
 2556:               formname => 'document.cu',
 2557:               kerb_def_dom => 'MSU.EDU',
 2558:               @_,
 2559:               );
 2560:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2561:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2562:     if (defined($in{'curr_authtype'})) {
 2563:         if ($in{'curr_authtype'} eq 'fsys') {
 2564:             if ($can_assign{'fsys'}) {
 2565:                 $fsyscheck = 'checked="checked" ';
 2566:                 if (defined($in{'mode'})) {
 2567:                     if ($in{'mode'} eq 'modifyuser') {
 2568:                         $fsyscheck = '';
 2569:                     }
 2570:                 }
 2571:             } else {
 2572:                 $result = &mt('Currently Filesystem Authenticated.');
 2573:                 return $result;
 2574:             }           
 2575:         }
 2576:     } else {
 2577:         if ($authnum == 1) {
 2578:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2579:         }
 2580:     }
 2581:     if (!$can_assign{'fsys'}) {
 2582:         return;
 2583:     } elsif ($authtype eq '') {
 2584:         if (defined($in{'mode'})) {
 2585:             if ($in{'mode'} eq 'modifycourse') {
 2586:                 if ($authnum == 1) {
 2587:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2588:                 }
 2589:             }
 2590:         }
 2591:     }
 2592:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2593:     if ($authtype eq '') {
 2594:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2595:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2596:                     $jscall.'" />';
 2597:     }
 2598:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2599:                ' onchange="'.$jscall.'" />';
 2600:     $result = &mt
 2601:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2602:          '<label><input type="radio" name="login" value="fsys" '.
 2603:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2604:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2605:                   'onchange="'.$jscall.'" />');
 2606:     return $result;
 2607: }
 2608: 
 2609: sub get_assignable_auth {
 2610:     my ($dom) = @_;
 2611:     if ($dom eq '') {
 2612:         $dom = $env{'request.role.domain'};
 2613:     }
 2614:     my %can_assign = (
 2615:                           krb4 => 1,
 2616:                           krb5 => 1,
 2617:                           int  => 1,
 2618:                           loc  => 1,
 2619:                      );
 2620:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2621:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2622:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2623:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2624:             my $context;
 2625:             if ($env{'request.role'} =~ /^au/) {
 2626:                 $context = 'author';
 2627:             } elsif ($env{'request.role'} =~ /^dc/) {
 2628:                 $context = 'domain';
 2629:             } elsif ($env{'request.course.id'}) {
 2630:                 $context = 'course';
 2631:             }
 2632:             if ($context) {
 2633:                 if (ref($authhash->{$context}) eq 'HASH') {
 2634:                    %can_assign = %{$authhash->{$context}}; 
 2635:                 }
 2636:             }
 2637:         }
 2638:     }
 2639:     my $authnum = 0;
 2640:     foreach my $key (keys(%can_assign)) {
 2641:         if ($can_assign{$key}) {
 2642:             $authnum ++;
 2643:         }
 2644:     }
 2645:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2646:         $authnum --;
 2647:     }
 2648:     return ($authnum,%can_assign);
 2649: }
 2650: 
 2651: ###############################################################
 2652: ##    Get Kerberos Defaults for Domain                 ##
 2653: ###############################################################
 2654: ##
 2655: ## Returns default kerberos version and an associated argument
 2656: ## as listed in file domain.tab. If not listed, provides
 2657: ## appropriate default domain and kerberos version.
 2658: ##
 2659: #-------------------------------------------
 2660: 
 2661: =pod
 2662: 
 2663: =item * &get_kerberos_defaults()
 2664: 
 2665: get_kerberos_defaults($target_domain) returns the default kerberos
 2666: version and domain. If not found, it defaults to version 4 and the 
 2667: domain of the server.
 2668: 
 2669: =over 4
 2670: 
 2671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2672: 
 2673: =back
 2674: 
 2675: =back
 2676: 
 2677: =cut
 2678: 
 2679: #-------------------------------------------
 2680: sub get_kerberos_defaults {
 2681:     my $domain=shift;
 2682:     my ($krbdef,$krbdefdom);
 2683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2685:         $krbdef = $domdefaults{'auth_def'};
 2686:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2687:     } else {
 2688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2689:         my $krbdefdom=$1;
 2690:         $krbdefdom=~tr/a-z/A-Z/;
 2691:         $krbdef = "krb4";
 2692:     }
 2693:     return ($krbdef,$krbdefdom);
 2694: }
 2695: 
 2696: 
 2697: ###############################################################
 2698: ##                Thesaurus Functions                        ##
 2699: ###############################################################
 2700: 
 2701: =pod
 2702: 
 2703: =head1 Thesaurus Functions
 2704: 
 2705: =over 4
 2706: 
 2707: =item * &initialize_keywords()
 2708: 
 2709: Initializes the package variable %Keywords if it is empty.  Uses the
 2710: package variable $thesaurus_db_file.
 2711: 
 2712: =cut
 2713: 
 2714: ###################################################
 2715: 
 2716: sub initialize_keywords {
 2717:     return 1 if (scalar keys(%Keywords));
 2718:     # If we are here, %Keywords is empty, so fill it up
 2719:     #   Make sure the file we need exists...
 2720:     if (! -e $thesaurus_db_file) {
 2721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2722:                                  " failed because it does not exist");
 2723:         return 0;
 2724:     }
 2725:     #   Set up the hash as a database
 2726:     my %thesaurus_db;
 2727:     if (! tie(%thesaurus_db,'GDBM_File',
 2728:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2730:                                  $thesaurus_db_file);
 2731:         return 0;
 2732:     } 
 2733:     #  Get the average number of appearances of a word.
 2734:     my $avecount = $thesaurus_db{'average.count'};
 2735:     #  Put keywords (those that appear > average) into %Keywords
 2736:     while (my ($word,$data)=each (%thesaurus_db)) {
 2737:         my ($count,undef) = split /:/,$data;
 2738:         $Keywords{$word}++ if ($count > $avecount);
 2739:     }
 2740:     untie %thesaurus_db;
 2741:     # Remove special values from %Keywords.
 2742:     foreach my $value ('total.count','average.count') {
 2743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2744:   }
 2745:     return 1;
 2746: }
 2747: 
 2748: ###################################################
 2749: 
 2750: =pod
 2751: 
 2752: =item * &keyword($word)
 2753: 
 2754: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2755: than the average number of times in the thesaurus database.  Calls 
 2756: &initialize_keywords
 2757: 
 2758: =cut
 2759: 
 2760: ###################################################
 2761: 
 2762: sub keyword {
 2763:     return if (!&initialize_keywords());
 2764:     my $word=lc(shift());
 2765:     $word=~s/\W//g;
 2766:     return exists($Keywords{$word});
 2767: }
 2768: 
 2769: ###############################################################
 2770: 
 2771: =pod 
 2772: 
 2773: =item * &get_related_words()
 2774: 
 2775: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2776: an array of words.  If the keyword is not in the thesaurus, an empty array
 2777: will be returned.  The order of the words returned is determined by the
 2778: database which holds them.
 2779: 
 2780: Uses global $thesaurus_db_file.
 2781: 
 2782: =cut
 2783: 
 2784: ###############################################################
 2785: sub get_related_words {
 2786:     my $keyword = shift;
 2787:     my %thesaurus_db;
 2788:     if (! -e $thesaurus_db_file) {
 2789:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2790:                                  "failed because the file does not exist");
 2791:         return ();
 2792:     }
 2793:     if (! tie(%thesaurus_db,'GDBM_File',
 2794:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2795:         return ();
 2796:     } 
 2797:     my @Words=();
 2798:     my $count=0;
 2799:     if (exists($thesaurus_db{$keyword})) {
 2800: 	# The first element is the number of times
 2801: 	# the word appears.  We do not need it now.
 2802: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2803: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2804: 	my $threshold=$mostfrequentcount/10;
 2805:         foreach my $possibleword (@RelatedWords) {
 2806:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2807:             if ($wordcount>$threshold) {
 2808: 		push(@Words,$word);
 2809:                 $count++;
 2810:                 if ($count>10) { last; }
 2811: 	    }
 2812:         }
 2813:     }
 2814:     untie %thesaurus_db;
 2815:     return @Words;
 2816: }
 2817: 
 2818: =pod
 2819: 
 2820: =back
 2821: 
 2822: =cut
 2823: 
 2824: # -------------------------------------------------------------- Plaintext name
 2825: =pod
 2826: 
 2827: =head1 User Name Functions
 2828: 
 2829: =over 4
 2830: 
 2831: =item * &plainname($uname,$udom,$first)
 2832: 
 2833: Takes a users logon name and returns it as a string in
 2834: "first middle last generation" form 
 2835: if $first is set to 'lastname' then it returns it as
 2836: 'lastname generation, firstname middlename' if their is a lastname
 2837: 
 2838: =cut
 2839: 
 2840: 
 2841: ###############################################################
 2842: sub plainname {
 2843:     my ($uname,$udom,$first)=@_;
 2844:     return if (!defined($uname) || !defined($udom));
 2845:     my %names=&getnames($uname,$udom);
 2846:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2847: 					  $names{'middlename'},
 2848: 					  $names{'lastname'},
 2849: 					  $names{'generation'},$first);
 2850:     $name=~s/^\s+//;
 2851:     $name=~s/\s+$//;
 2852:     $name=~s/\s+/ /g;
 2853:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2854:     return $name;
 2855: }
 2856: 
 2857: # -------------------------------------------------------------------- Nickname
 2858: =pod
 2859: 
 2860: =item * &nickname($uname,$udom)
 2861: 
 2862: Gets a users name and returns it as a string as
 2863: 
 2864: "&quot;nickname&quot;"
 2865: 
 2866: if the user has a nickname or
 2867: 
 2868: "first middle last generation"
 2869: 
 2870: if the user does not
 2871: 
 2872: =cut
 2873: 
 2874: sub nickname {
 2875:     my ($uname,$udom)=@_;
 2876:     return if (!defined($uname) || !defined($udom));
 2877:     my %names=&getnames($uname,$udom);
 2878:     my $name=$names{'nickname'};
 2879:     if ($name) {
 2880:        $name='&quot;'.$name.'&quot;'; 
 2881:     } else {
 2882:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2883: 	     $names{'lastname'}.' '.$names{'generation'};
 2884:        $name=~s/\s+$//;
 2885:        $name=~s/\s+/ /g;
 2886:     }
 2887:     return $name;
 2888: }
 2889: 
 2890: sub getnames {
 2891:     my ($uname,$udom)=@_;
 2892:     return if (!defined($uname) || !defined($udom));
 2893:     if ($udom eq 'public' && $uname eq 'public') {
 2894: 	return ('lastname' => &mt('Public'));
 2895:     }
 2896:     my $id=$uname.':'.$udom;
 2897:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2898:     if ($cached) {
 2899: 	return %{$names};
 2900:     } else {
 2901: 	my %loadnames=&Apache::lonnet::get('environment',
 2902:                     ['firstname','middlename','lastname','generation','nickname'],
 2903: 					 $udom,$uname);
 2904: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2905: 	return %loadnames;
 2906:     }
 2907: }
 2908: 
 2909: # -------------------------------------------------------------------- getemails
 2910: 
 2911: =pod
 2912: 
 2913: =item * &getemails($uname,$udom)
 2914: 
 2915: Gets a user's email information and returns it as a hash with keys:
 2916: notification, critnotification, permanentemail
 2917: 
 2918: For notification and critnotification, values are comma-separated lists 
 2919: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2920:  
 2921: 
 2922: =cut
 2923: 
 2924: 
 2925: sub getemails {
 2926:     my ($uname,$udom)=@_;
 2927:     if ($udom eq 'public' && $uname eq 'public') {
 2928: 	return;
 2929:     }
 2930:     if (!$udom) { $udom=$env{'user.domain'}; }
 2931:     if (!$uname) { $uname=$env{'user.name'}; }
 2932:     my $id=$uname.':'.$udom;
 2933:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2934:     if ($cached) {
 2935: 	return %{$names};
 2936:     } else {
 2937: 	my %loadnames=&Apache::lonnet::get('environment',
 2938:                     			   ['notification','critnotification',
 2939: 					    'permanentemail'],
 2940: 					   $udom,$uname);
 2941: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2942: 	return %loadnames;
 2943:     }
 2944: }
 2945: 
 2946: sub flush_email_cache {
 2947:     my ($uname,$udom)=@_;
 2948:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2949:     if (!$uname) { $uname=$env{'user.name'};   }
 2950:     return if ($udom eq 'public' && $uname eq 'public');
 2951:     my $id=$uname.':'.$udom;
 2952:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2953: }
 2954: 
 2955: # -------------------------------------------------------------------- getlangs
 2956: 
 2957: =pod
 2958: 
 2959: =item * &getlangs($uname,$udom)
 2960: 
 2961: Gets a user's language preference and returns it as a hash with key:
 2962: language.
 2963: 
 2964: =cut
 2965: 
 2966: 
 2967: sub getlangs {
 2968:     my ($uname,$udom) = @_;
 2969:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2970:     if (!$uname) { $uname=$env{'user.name'};   }
 2971:     my $id=$uname.':'.$udom;
 2972:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2973:     if ($cached) {
 2974:         return %{$langs};
 2975:     } else {
 2976:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2977:                                            $udom,$uname);
 2978:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2979:         return %loadlangs;
 2980:     }
 2981: }
 2982: 
 2983: sub flush_langs_cache {
 2984:     my ($uname,$udom)=@_;
 2985:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2986:     if (!$uname) { $uname=$env{'user.name'};   }
 2987:     return if ($udom eq 'public' && $uname eq 'public');
 2988:     my $id=$uname.':'.$udom;
 2989:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2990: }
 2991: 
 2992: # ------------------------------------------------------------------ Screenname
 2993: 
 2994: =pod
 2995: 
 2996: =item * &screenname($uname,$udom)
 2997: 
 2998: Gets a users screenname and returns it as a string
 2999: 
 3000: =cut
 3001: 
 3002: sub screenname {
 3003:     my ($uname,$udom)=@_;
 3004:     if ($uname eq $env{'user.name'} &&
 3005: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3006:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3007:     return $names{'screenname'};
 3008: }
 3009: 
 3010: 
 3011: # ------------------------------------------------------------- Confirm Wrapper
 3012: =pod
 3013: 
 3014: =item confirmwrapper
 3015: 
 3016: Wrap messages about completion of operation in box
 3017: 
 3018: =cut
 3019: 
 3020: sub confirmwrapper {
 3021:     my ($message)=@_;
 3022:     if ($message) {
 3023:         return "\n".'<div class="LC_confirm_box">'."\n"
 3024:                .$message."\n"
 3025:                .'</div>'."\n";
 3026:     } else {
 3027:         return $message;
 3028:     }
 3029: }
 3030: 
 3031: # ------------------------------------------------------------- Message Wrapper
 3032: 
 3033: sub messagewrapper {
 3034:     my ($link,$username,$domain,$subject,$text)=@_;
 3035:     return 
 3036:         '<a href="/adm/email?compose=individual&amp;'.
 3037:         'recname='.$username.'&amp;recdom='.$domain.
 3038: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3039:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3040: }
 3041: 
 3042: # --------------------------------------------------------------- Notes Wrapper
 3043: 
 3044: sub noteswrapper {
 3045:     my ($link,$un,$do)=@_;
 3046:     return 
 3047: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3048: }
 3049: 
 3050: # ------------------------------------------------------------- Aboutme Wrapper
 3051: 
 3052: sub aboutmewrapper {
 3053:     my ($link,$username,$domain,$target)=@_;
 3054:     if (!defined($username)  && !defined($domain)) {
 3055:         return;
 3056:     }
 3057:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3058: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3059: }
 3060: 
 3061: # ------------------------------------------------------------ Syllabus Wrapper
 3062: 
 3063: sub syllabuswrapper {
 3064:     my ($linktext,$coursedir,$domain)=@_;
 3065:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3066: }
 3067: 
 3068: # -----------------------------------------------------------------------------
 3069: 
 3070: sub track_student_link {
 3071:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3072:     my $link ="/adm/trackstudent?";
 3073:     my $title = 'View recent activity';
 3074:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3075:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3076:         $link .= "selected_student=$sname:$sdom";
 3077:         $title .= ' of this student';
 3078:     } 
 3079:     if (defined($target) && $target !~ /^\s*$/) {
 3080:         $target = qq{target="$target"};
 3081:     } else {
 3082:         $target = '';
 3083:     }
 3084:     if ($start) { $link.='&amp;start='.$start; }
 3085:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3086:     $title = &mt($title);
 3087:     $linktext = &mt($linktext);
 3088:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3089: 	&help_open_topic('View_recent_activity');
 3090: }
 3091: 
 3092: sub slot_reservations_link {
 3093:     my ($linktext,$sname,$sdom,$target) = @_;
 3094:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3095:     my $title = 'View slot reservation history';
 3096:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3097:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3098:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3099:         $title .= ' of this student';
 3100:     }
 3101:     if (defined($target) && $target !~ /^\s*$/) {
 3102:         $target = qq{target="$target"};
 3103:     } else {
 3104:         $target = '';
 3105:     }
 3106:     $title = &mt($title);
 3107:     $linktext = &mt($linktext);
 3108:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3109: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3110: 
 3111: }
 3112: 
 3113: # ===================================================== Display a student photo
 3114: 
 3115: 
 3116: sub student_image_tag {
 3117:     my ($domain,$user)=@_;
 3118:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3119:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3120: 	return '<img src="'.$imgsrc.'" align="right" />';
 3121:     } else {
 3122: 	return '';
 3123:     }
 3124: }
 3125: 
 3126: =pod
 3127: 
 3128: =back
 3129: 
 3130: =head1 Access .tab File Data
 3131: 
 3132: =over 4
 3133: 
 3134: =item * &languageids() 
 3135: 
 3136: returns list of all language ids
 3137: 
 3138: =cut
 3139: 
 3140: sub languageids {
 3141:     return sort(keys(%language));
 3142: }
 3143: 
 3144: =pod
 3145: 
 3146: =item * &languagedescription() 
 3147: 
 3148: returns description of a specified language id
 3149: 
 3150: =cut
 3151: 
 3152: sub languagedescription {
 3153:     my $code=shift;
 3154:     return  ($supported_language{$code}?'* ':'').
 3155:             $language{$code}.
 3156: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3157: }
 3158: 
 3159: sub plainlanguagedescription {
 3160:     my $code=shift;
 3161:     return $language{$code};
 3162: }
 3163: 
 3164: sub supportedlanguagecode {
 3165:     my $code=shift;
 3166:     return $supported_language{$code};
 3167: }
 3168: 
 3169: =pod
 3170: 
 3171: =item * &copyrightids() 
 3172: 
 3173: returns list of all copyrights
 3174: 
 3175: =cut
 3176: 
 3177: sub copyrightids {
 3178:     return sort(keys(%cprtag));
 3179: }
 3180: 
 3181: =pod
 3182: 
 3183: =item * &copyrightdescription() 
 3184: 
 3185: returns description of a specified copyright id
 3186: 
 3187: =cut
 3188: 
 3189: sub copyrightdescription {
 3190:     return &mt($cprtag{shift(@_)});
 3191: }
 3192: 
 3193: =pod
 3194: 
 3195: =item * &source_copyrightids() 
 3196: 
 3197: returns list of all source copyrights
 3198: 
 3199: =cut
 3200: 
 3201: sub source_copyrightids {
 3202:     return sort(keys(%scprtag));
 3203: }
 3204: 
 3205: =pod
 3206: 
 3207: =item * &source_copyrightdescription() 
 3208: 
 3209: returns description of a specified source copyright id
 3210: 
 3211: =cut
 3212: 
 3213: sub source_copyrightdescription {
 3214:     return &mt($scprtag{shift(@_)});
 3215: }
 3216: 
 3217: =pod
 3218: 
 3219: =item * &filecategories() 
 3220: 
 3221: returns list of all file categories
 3222: 
 3223: =cut
 3224: 
 3225: sub filecategories {
 3226:     return sort(keys(%category_extensions));
 3227: }
 3228: 
 3229: =pod
 3230: 
 3231: =item * &filecategorytypes() 
 3232: 
 3233: returns list of file types belonging to a given file
 3234: category
 3235: 
 3236: =cut
 3237: 
 3238: sub filecategorytypes {
 3239:     my ($cat) = @_;
 3240:     return @{$category_extensions{lc($cat)}};
 3241: }
 3242: 
 3243: =pod
 3244: 
 3245: =item * &fileembstyle() 
 3246: 
 3247: returns embedding style for a specified file type
 3248: 
 3249: =cut
 3250: 
 3251: sub fileembstyle {
 3252:     return $fe{lc(shift(@_))};
 3253: }
 3254: 
 3255: sub filemimetype {
 3256:     return $fm{lc(shift(@_))};
 3257: }
 3258: 
 3259: 
 3260: sub filecategoryselect {
 3261:     my ($name,$value)=@_;
 3262:     return &select_form($value,$name,
 3263: 			{'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3264: }
 3265: 
 3266: =pod
 3267: 
 3268: =item * &filedescription() 
 3269: 
 3270: returns description for a specified file type
 3271: 
 3272: =cut
 3273: 
 3274: sub filedescription {
 3275:     my $file_description = $fd{lc(shift())};
 3276:     $file_description =~ s:([\[\]]):~$1:g;
 3277:     return &mt($file_description);
 3278: }
 3279: 
 3280: =pod
 3281: 
 3282: =item * &filedescriptionex() 
 3283: 
 3284: returns description for a specified file type with
 3285: extra formatting
 3286: 
 3287: =cut
 3288: 
 3289: sub filedescriptionex {
 3290:     my $ex=shift;
 3291:     my $file_description = $fd{lc($ex)};
 3292:     $file_description =~ s:([\[\]]):~$1:g;
 3293:     return '.'.$ex.' '.&mt($file_description);
 3294: }
 3295: 
 3296: # End of .tab access
 3297: =pod
 3298: 
 3299: =back
 3300: 
 3301: =cut
 3302: 
 3303: # ------------------------------------------------------------------ File Types
 3304: sub fileextensions {
 3305:     return sort(keys(%fe));
 3306: }
 3307: 
 3308: # ----------------------------------------------------------- Display Languages
 3309: # returns a hash with all desired display languages
 3310: #
 3311: 
 3312: sub display_languages {
 3313:     my %languages=();
 3314:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3315: 	$languages{$lang}=1;
 3316:     }
 3317:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3318:     if ($env{'form.displaylanguage'}) {
 3319: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3320: 	    $languages{$lang}=1;
 3321:         }
 3322:     }
 3323:     return %languages;
 3324: }
 3325: 
 3326: sub languages {
 3327:     my ($possible_langs) = @_;
 3328:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3329:     if (!ref($possible_langs)) {
 3330: 	if( wantarray ) {
 3331: 	    return @preferred_langs;
 3332: 	} else {
 3333: 	    return $preferred_langs[0];
 3334: 	}
 3335:     }
 3336:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3337:     my @preferred_possibilities;
 3338:     foreach my $preferred_lang (@preferred_langs) {
 3339: 	if (exists($possibilities{$preferred_lang})) {
 3340: 	    push(@preferred_possibilities, $preferred_lang);
 3341: 	}
 3342:     }
 3343:     if( wantarray ) {
 3344: 	return @preferred_possibilities;
 3345:     }
 3346:     return $preferred_possibilities[0];
 3347: }
 3348: 
 3349: sub user_lang {
 3350:     my ($touname,$toudom,$fromcid) = @_;
 3351:     my @userlangs;
 3352:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3353:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3354:                     $env{'course.'.$fromcid.'.languages'}));
 3355:     } else {
 3356:         my %langhash = &getlangs($touname,$toudom);
 3357:         if ($langhash{'languages'} ne '') {
 3358:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3359:         } else {
 3360:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3361:             if ($domdefs{'lang_def'} ne '') {
 3362:                 @userlangs = ($domdefs{'lang_def'});
 3363:             }
 3364:         }
 3365:     }
 3366:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3367:     my $user_lh = Apache::localize->get_handle(@languages);
 3368:     return $user_lh;
 3369: }
 3370: 
 3371: 
 3372: ###############################################################
 3373: ##               Student Answer Attempts                     ##
 3374: ###############################################################
 3375: 
 3376: =pod
 3377: 
 3378: =head1 Alternate Problem Views
 3379: 
 3380: =over 4
 3381: 
 3382: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3383:     $getattempt, $regexp, $gradesub)
 3384: 
 3385: Return string with previous attempt on problem. Arguments:
 3386: 
 3387: =over 4
 3388: 
 3389: =item * $symb: Problem, including path
 3390: 
 3391: =item * $username: username of the desired student
 3392: 
 3393: =item * $domain: domain of the desired student
 3394: 
 3395: =item * $course: Course ID
 3396: 
 3397: =item * $getattempt: Leave blank for all attempts, otherwise put
 3398:     something
 3399: 
 3400: =item * $regexp: if string matches this regexp, the string will be
 3401:     sent to $gradesub
 3402: 
 3403: =item * $gradesub: routine that processes the string if it matches $regexp
 3404: 
 3405: =back
 3406: 
 3407: The output string is a table containing all desired attempts, if any.
 3408: 
 3409: =cut
 3410: 
 3411: sub get_previous_attempt {
 3412:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3413:   my $prevattempts='';
 3414:   no strict 'refs';
 3415:   if ($symb) {
 3416:     my (%returnhash)=
 3417:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3418:     if ($returnhash{'version'}) {
 3419:       my %lasthash=();
 3420:       my $version;
 3421:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3422:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3423: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3424:         }
 3425:       }
 3426:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3427:       $prevattempts.='<th>'.&mt('History').'</th>';
 3428:       my (%typeparts,%lasthidden);
 3429:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3430:       foreach my $key (sort(keys(%lasthash))) {
 3431: 	my ($ign,@parts) = split(/\./,$key);
 3432: 	if ($#parts > 0) {
 3433: 	  my $data=$parts[-1];
 3434:           next if ($data eq 'foilorder');
 3435: 	  pop(@parts);
 3436:           if ($data eq 'type') {
 3437:               unless ($showsurv) {
 3438:                   my $id = join(',',@parts);
 3439:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3440:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3441:                       $lasthidden{$ign.'.'.$id} = 1;
 3442:                   }
 3443:               }
 3444:               delete($lasthash{$key});
 3445:           } else {
 3446: 	      $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3447:           }
 3448: 	} else {
 3449: 	  if ($#parts == 0) {
 3450: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3451: 	  } else {
 3452: 	    $prevattempts.='<th>'.$ign.'</th>';
 3453: 	  }
 3454: 	}
 3455:       }
 3456:       $prevattempts.=&end_data_table_header_row();
 3457:       if ($getattempt eq '') {
 3458: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3459:             my @hidden;
 3460:             if (%typeparts) {
 3461:                 foreach my $id (keys(%typeparts)) {
 3462:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3463:                         push(@hidden,$id);
 3464:                     }
 3465:                 }
 3466:             }
 3467:             $prevattempts.=&start_data_table_row().
 3468:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3469:             if (@hidden) {
 3470:                 foreach my $key (sort(keys(%lasthash))) {
 3471:                     next if ($key =~ /\.foilorder$/);
 3472:                     my $hide;
 3473:                     foreach my $id (@hidden) {
 3474:                         if ($key =~ /^\Q$id\E/) {
 3475:                             $hide = 1;
 3476:                             last;
 3477:                         }
 3478:                     }
 3479:                     if ($hide) {
 3480:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3481:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3482:                             my $value = &format_previous_attempt_value($key,
 3483:                                              $returnhash{$version.':'.$key});
 3484:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3485:                         } else {
 3486:                             $prevattempts.='<td>&nbsp;</td>';
 3487:                         }
 3488:                     } else {
 3489:                         if ($key =~ /\./) {
 3490:                             my $value = &format_previous_attempt_value($key,
 3491:                                               $returnhash{$version.':'.$key});
 3492:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3493:                         } else {
 3494:                             $prevattempts.='<td>&nbsp;</td>';
 3495:                         }
 3496:                     }
 3497:                 }
 3498:             } else {
 3499: 	        foreach my $key (sort(keys(%lasthash))) {
 3500:                     next if ($key =~ /\.foilorder$/);
 3501: 		    my $value = &format_previous_attempt_value($key,
 3502: 			            $returnhash{$version.':'.$key});
 3503: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3504: 	        }
 3505:             }
 3506: 	    $prevattempts.=&end_data_table_row();
 3507: 	 }
 3508:       }
 3509:       my @currhidden = keys(%lasthidden);
 3510:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3511:       foreach my $key (sort(keys(%lasthash))) {
 3512:           next if ($key =~ /\.foilorder$/);
 3513:           if (%typeparts) {
 3514:               my $hidden;
 3515:               foreach my $id (@currhidden) {
 3516:                   if ($key =~ /^\Q$id\E/) {
 3517:                       $hidden = 1;
 3518:                       last;
 3519:                   }
 3520:               }
 3521:               if ($hidden) {
 3522:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3523:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3524:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3525:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3526:                           $value = &$gradesub($value);
 3527:                       }
 3528:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3529:                   } else {
 3530:                       $prevattempts.='<td>&nbsp;</td>';
 3531:                   }
 3532:               } else {
 3533:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3534:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3535:                       $value = &$gradesub($value);
 3536:                   }
 3537:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3538:               }
 3539:           } else {
 3540: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3541: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3542:                   $value = &$gradesub($value);
 3543:               }
 3544: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3545:           }
 3546:       }
 3547:       $prevattempts.= &end_data_table_row().&end_data_table();
 3548:     } else {
 3549:       $prevattempts=
 3550: 	  &start_data_table().&start_data_table_row().
 3551: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3552: 	  &end_data_table_row().&end_data_table();
 3553:     }
 3554:   } else {
 3555:     $prevattempts=
 3556: 	  &start_data_table().&start_data_table_row().
 3557: 	  '<td>'.&mt('No data.').'</td>'.
 3558: 	  &end_data_table_row().&end_data_table();
 3559:   }
 3560: }
 3561: 
 3562: sub format_previous_attempt_value {
 3563:     my ($key,$value) = @_;
 3564:     if ($key =~ /timestamp/) {
 3565: 	$value = &Apache::lonlocal::locallocaltime($value);
 3566:     } elsif (ref($value) eq 'ARRAY') {
 3567: 	$value = '('.join(', ', @{ $value }).')';
 3568:     } elsif ($key =~ /answerstring$/) {
 3569:         my %answers = &Apache::lonnet::str2hash($value);
 3570:         my @anskeys = sort(keys(%answers));
 3571:         if (@anskeys == 1) {
 3572:             my $answer = $answers{$anskeys[0]};
 3573:             if ($answer =~ m{\0}) {
 3574:                 $answer =~ s{\0}{,}g;
 3575:             }
 3576:             my $tag_internal_answer_name = 'INTERNAL';
 3577:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3578:                 $value = $answer;
 3579:             } else {
 3580:                 $value = $anskeys[0].'='.$answer;
 3581:             }
 3582:         } else {
 3583:             foreach my $ans (@anskeys) {
 3584:                 my $answer = $answers{$ans};
 3585:                 if ($answer =~ m{\0}) {
 3586:                     $answer =~ s{\0}{,}g;
 3587:                 }
 3588:                 $value .=  $ans.'='.$answer.'<br />';;
 3589:             }
 3590:         }
 3591:     } else {
 3592: 	$value = &unescape($value);
 3593:     }
 3594:     return $value;
 3595: }
 3596: 
 3597: 
 3598: sub relative_to_absolute {
 3599:     my ($url,$output)=@_;
 3600:     my $parser=HTML::TokeParser->new(\$output);
 3601:     my $token;
 3602:     my $thisdir=$url;
 3603:     my @rlinks=();
 3604:     while ($token=$parser->get_token) {
 3605: 	if ($token->[0] eq 'S') {
 3606: 	    if ($token->[1] eq 'a') {
 3607: 		if ($token->[2]->{'href'}) {
 3608: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3609: 		}
 3610: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3611: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3612: 	    } elsif ($token->[1] eq 'base') {
 3613: 		$thisdir=$token->[2]->{'href'};
 3614: 	    }
 3615: 	}
 3616:     }
 3617:     $thisdir=~s-/[^/]*$--;
 3618:     foreach my $link (@rlinks) {
 3619: 	unless (($link=~/^https?\:\/\//i) ||
 3620: 		($link=~/^\//) ||
 3621: 		($link=~/^javascript:/i) ||
 3622: 		($link=~/^mailto:/i) ||
 3623: 		($link=~/^\#/)) {
 3624: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3625: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3626: 	}
 3627:     }
 3628: # -------------------------------------------------- Deal with Applet codebases
 3629:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3630:     return $output;
 3631: }
 3632: 
 3633: =pod
 3634: 
 3635: =item * &get_student_view()
 3636: 
 3637: show a snapshot of what student was looking at
 3638: 
 3639: =cut
 3640: 
 3641: sub get_student_view {
 3642:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3643:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3644:   my (%form);
 3645:   my @elements=('symb','courseid','domain','username');
 3646:   foreach my $element (@elements) {
 3647:       $form{'grade_'.$element}=eval '$'.$element #'
 3648:   }
 3649:   if (defined($moreenv)) {
 3650:       %form=(%form,%{$moreenv});
 3651:   }
 3652:   if (defined($target)) { $form{'grade_target'} = $target; }
 3653:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3654:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3655:   $userview=~s/\<body[^\>]*\>//gi;
 3656:   $userview=~s/\<\/body\>//gi;
 3657:   $userview=~s/\<html\>//gi;
 3658:   $userview=~s/\<\/html\>//gi;
 3659:   $userview=~s/\<head\>//gi;
 3660:   $userview=~s/\<\/head\>//gi;
 3661:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3662:   $userview=&relative_to_absolute($feedurl,$userview);
 3663:   if (wantarray) {
 3664:      return ($userview,$response);
 3665:   } else {
 3666:      return $userview;
 3667:   }
 3668: }
 3669: 
 3670: sub get_student_view_with_retries {
 3671:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3672: 
 3673:     my $ok = 0;                 # True if we got a good response.
 3674:     my $content;
 3675:     my $response;
 3676: 
 3677:     # Try to get the student_view done. within the retries count:
 3678:     
 3679:     do {
 3680:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3681:          $ok      = $response->is_success;
 3682:          if (!$ok) {
 3683:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3684:          }
 3685:          $retries--;
 3686:     } while (!$ok && ($retries > 0));
 3687:     
 3688:     if (!$ok) {
 3689:        $content = '';          # On error return an empty content.
 3690:     }
 3691:     if (wantarray) {
 3692:        return ($content, $response);
 3693:     } else {
 3694:        return $content;
 3695:     }
 3696: }
 3697: 
 3698: =pod
 3699: 
 3700: =item * &get_student_answers() 
 3701: 
 3702: show a snapshot of how student was answering problem
 3703: 
 3704: =cut
 3705: 
 3706: sub get_student_answers {
 3707:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3708:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3709:   my (%moreenv);
 3710:   my @elements=('symb','courseid','domain','username');
 3711:   foreach my $element (@elements) {
 3712:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3713:   }
 3714:   $moreenv{'grade_target'}='answer';
 3715:   %moreenv=(%form,%moreenv);
 3716:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3717:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3718:   return $userview;
 3719: }
 3720: 
 3721: =pod
 3722: 
 3723: =item * &submlink()
 3724: 
 3725: Inputs: $text $uname $udom $symb $target
 3726: 
 3727: Returns: A link to grades.pm such as to see the SUBM view of a student
 3728: 
 3729: =cut
 3730: 
 3731: ###############################################
 3732: sub submlink {
 3733:     my ($text,$uname,$udom,$symb,$target)=@_;
 3734:     if (!($uname && $udom)) {
 3735: 	(my $cursymb, my $courseid,$udom,$uname)=
 3736: 	    &Apache::lonnet::whichuser($symb);
 3737: 	if (!$symb) { $symb=$cursymb; }
 3738:     }
 3739:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3740:     $symb=&escape($symb);
 3741:     if ($target) { $target=" target=\"$target\""; }
 3742:     return
 3743:         '<a href="/adm/grades?command=submission'.
 3744:         '&amp;symb='.$symb.
 3745:         '&amp;student='.$uname.
 3746:         '&amp;userdom='.$udom.'"'.
 3747:         $target.'>'.$text.'</a>';
 3748: }
 3749: ##############################################
 3750: 
 3751: =pod
 3752: 
 3753: =item * &pgrdlink()
 3754: 
 3755: Inputs: $text $uname $udom $symb $target
 3756: 
 3757: Returns: A link to grades.pm such as to see the PGRD view of a student
 3758: 
 3759: =cut
 3760: 
 3761: ###############################################
 3762: sub pgrdlink {
 3763:     my $link=&submlink(@_);
 3764:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3765:     return $link;
 3766: }
 3767: ##############################################
 3768: 
 3769: =pod
 3770: 
 3771: =item * &pprmlink()
 3772: 
 3773: Inputs: $text $uname $udom $symb $target
 3774: 
 3775: Returns: A link to parmset.pm such as to see the PPRM view of a
 3776: student and a specific resource
 3777: 
 3778: =cut
 3779: 
 3780: ###############################################
 3781: sub pprmlink {
 3782:     my ($text,$uname,$udom,$symb,$target)=@_;
 3783:     if (!($uname && $udom)) {
 3784: 	(my $cursymb, my $courseid,$udom,$uname)=
 3785: 	    &Apache::lonnet::whichuser($symb);
 3786: 	if (!$symb) { $symb=$cursymb; }
 3787:     }
 3788:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3789:     $symb=&escape($symb);
 3790:     if ($target) { $target="target=\"$target\""; }
 3791:     return '<a href="/adm/parmset?command=set&amp;'.
 3792: 	'symb='.$symb.'&amp;uname='.$uname.
 3793: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3794: }
 3795: ##############################################
 3796: 
 3797: =pod
 3798: 
 3799: =back
 3800: 
 3801: =cut
 3802: 
 3803: ###############################################
 3804: 
 3805: 
 3806: sub timehash {
 3807:     my ($thistime) = @_;
 3808:     my $timezone = &Apache::lonlocal::gettimezone();
 3809:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3810:                      ->set_time_zone($timezone);
 3811:     my $wday = $dt->day_of_week();
 3812:     if ($wday == 7) { $wday = 0; }
 3813:     return ( 'second' => $dt->second(),
 3814:              'minute' => $dt->minute(),
 3815:              'hour'   => $dt->hour(),
 3816:              'day'     => $dt->day_of_month(),
 3817:              'month'   => $dt->month(),
 3818:              'year'    => $dt->year(),
 3819:              'weekday' => $wday,
 3820:              'dayyear' => $dt->day_of_year(),
 3821:              'dlsav'   => $dt->is_dst() );
 3822: }
 3823: 
 3824: sub utc_string {
 3825:     my ($date)=@_;
 3826:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3827: }
 3828: 
 3829: sub maketime {
 3830:     my %th=@_;
 3831:     my ($epoch_time,$timezone,$dt);
 3832:     $timezone = &Apache::lonlocal::gettimezone();
 3833:     eval {
 3834:         $dt = DateTime->new( year   => $th{'year'},
 3835:                              month  => $th{'month'},
 3836:                              day    => $th{'day'},
 3837:                              hour   => $th{'hour'},
 3838:                              minute => $th{'minute'},
 3839:                              second => $th{'second'},
 3840:                              time_zone => $timezone,
 3841:                          );
 3842:     };
 3843:     if (!$@) {
 3844:         $epoch_time = $dt->epoch;
 3845:         if ($epoch_time) {
 3846:             return $epoch_time;
 3847:         }
 3848:     }
 3849:     return POSIX::mktime(
 3850:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3851:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3852: }
 3853: 
 3854: #########################################
 3855: 
 3856: sub findallcourses {
 3857:     my ($roles,$uname,$udom) = @_;
 3858:     my %roles;
 3859:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3860:     my %courses;
 3861:     my $now=time;
 3862:     if (!defined($uname)) {
 3863:         $uname = $env{'user.name'};
 3864:     }
 3865:     if (!defined($udom)) {
 3866:         $udom = $env{'user.domain'};
 3867:     }
 3868:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3869:         my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 3870:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
 3871:                                               $extra);
 3872:         if (!%roles) {
 3873:             %roles = (
 3874:                        cc => 1,
 3875:                        co => 1,
 3876:                        in => 1,
 3877:                        ep => 1,
 3878:                        ta => 1,
 3879:                        cr => 1,
 3880:                        st => 1,
 3881:              );
 3882:         }
 3883:         foreach my $entry (keys(%roleshash)) {
 3884:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3885:             if ($trole =~ /^cr/) { 
 3886:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3887:             } else {
 3888:                 next if (!exists($roles{$trole}));
 3889:             }
 3890:             if ($tend) {
 3891:                 next if ($tend < $now);
 3892:             }
 3893:             if ($tstart) {
 3894:                 next if ($tstart > $now);
 3895:             }
 3896:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3897:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3898:             if ($secpart eq '') {
 3899:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3900:                 $sec = 'none';
 3901:                 $realsec = '';
 3902:             } else {
 3903:                 $cnum = $cnumpart;
 3904:                 ($sec,$role) = split(/_/,$secpart);
 3905:                 $realsec = $sec;
 3906:             }
 3907:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3908:         }
 3909:     } else {
 3910:         foreach my $key (keys(%env)) {
 3911: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3912:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3913: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3914: 	        next if ($role eq 'ca' || $role eq 'aa');
 3915: 	        next if (%roles && !exists($roles{$role}));
 3916: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3917:                 my $active=1;
 3918:                 if ($starttime) {
 3919: 		    if ($now<$starttime) { $active=0; }
 3920:                 }
 3921:                 if ($endtime) {
 3922:                     if ($now>$endtime) { $active=0; }
 3923:                 }
 3924:                 if ($active) {
 3925:                     if ($sec eq '') {
 3926:                         $sec = 'none';
 3927:                     }
 3928:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3929:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3930:                 }
 3931:             }
 3932:         }
 3933:     }
 3934:     return %courses;
 3935: }
 3936: 
 3937: ###############################################
 3938: 
 3939: sub blockcheck {
 3940:     my ($setters,$activity,$uname,$udom) = @_;
 3941: 
 3942:     if (!defined($udom)) {
 3943:         $udom = $env{'user.domain'};
 3944:     }
 3945:     if (!defined($uname)) {
 3946:         $uname = $env{'user.name'};
 3947:     }
 3948: 
 3949:     # If uname and udom are for a course, check for blocks in the course.
 3950: 
 3951:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3952:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3953:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3954:         return ($startblock,$endblock);
 3955:     }
 3956: 
 3957:     my $startblock = 0;
 3958:     my $endblock = 0;
 3959:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3960: 
 3961:     # If uname is for a user, and activity is course-specific, i.e.,
 3962:     # boards, chat or groups, check for blocking in current course only.
 3963: 
 3964:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3965:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3966:         foreach my $key (keys(%live_courses)) {
 3967:             if ($key ne $env{'request.course.id'}) {
 3968:                 delete($live_courses{$key});
 3969:             }
 3970:         }
 3971:     }
 3972: 
 3973:     my $otheruser = 0;
 3974:     my %own_courses;
 3975:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3976:         # Resource belongs to user other than current user.
 3977:         $otheruser = 1;
 3978:         # Gather courses for current user
 3979:         %own_courses = 
 3980:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3981:     }
 3982: 
 3983:     # Gather active course roles - course coordinator, instructor, 
 3984:     # exam proctor, ta, student, or custom role.
 3985: 
 3986:     foreach my $course (keys(%live_courses)) {
 3987:         my ($cdom,$cnum);
 3988:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3989:             $cdom = $env{'course.'.$course.'.domain'};
 3990:             $cnum = $env{'course.'.$course.'.num'};
 3991:         } else {
 3992:             ($cdom,$cnum) = split(/_/,$course); 
 3993:         }
 3994:         my $no_ownblock = 0;
 3995:         my $no_userblock = 0;
 3996:         if ($otheruser && $activity ne 'com') {
 3997:             # Check if current user has 'evb' priv for this
 3998:             if (defined($own_courses{$course})) {
 3999:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4000:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4001:                     if ($sec ne 'none') {
 4002:                         $checkrole .= '/'.$sec;
 4003:                     }
 4004:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4005:                         $no_ownblock = 1;
 4006:                         last;
 4007:                     }
 4008:                 }
 4009:             }
 4010:             # if they have 'evb' priv and are currently not playing student
 4011:             next if (($no_ownblock) &&
 4012:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4013:         }
 4014:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4015:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4016:             if ($sec ne 'none') {
 4017:                 $checkrole .= '/'.$sec;
 4018:             }
 4019:             if ($otheruser) {
 4020:                 # Resource belongs to user other than current user.
 4021:                 # Assemble privs for that user, and check for 'evb' priv.
 4022:                 my ($trole,$tdom,$tnum,$tsec);
 4023:                 my $entry = $live_courses{$course}{$sec};
 4024:                 if ($entry =~ /^cr/) {
 4025:                     ($trole,$tdom,$tnum,$tsec) = 
 4026:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4027:                 } else {
 4028:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4029:                 }
 4030:                 my ($spec,$area,$trest,%allroles,%userroles);
 4031:                 $area = '/'.$tdom.'/'.$tnum;
 4032:                 $trest = $tnum;
 4033:                 if ($tsec ne '') {
 4034:                     $area .= '/'.$tsec;
 4035:                     $trest .= '/'.$tsec;
 4036:                 }
 4037:                 $spec = $trole.'.'.$area;
 4038:                 if ($trole =~ /^cr/) {
 4039:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4040:                                                       $tdom,$spec,$trest,$area);
 4041:                 } else {
 4042:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4043:                                                        $tdom,$spec,$trest,$area);
 4044:                 }
 4045:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4046:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4047:                     if ($1) {
 4048:                         $no_userblock = 1;
 4049:                         last;
 4050:                     }
 4051:                 }
 4052:             } else {
 4053:                 # Resource belongs to current user
 4054:                 # Check for 'evb' priv via lonnet::allowed().
 4055:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4056:                     $no_ownblock = 1;
 4057:                     last;
 4058:                 }
 4059:             }
 4060:         }
 4061:         # if they have the evb priv and are currently not playing student
 4062:         next if (($no_ownblock) &&
 4063:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4064:         next if ($no_userblock);
 4065: 
 4066:         # Retrieve blocking times and identity of locker for course
 4067:         # of specified user, unless user has 'evb' privilege.
 4068:         
 4069:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4070:         if (($start != 0) && 
 4071:             (($startblock == 0) || ($startblock > $start))) {
 4072:             $startblock = $start;
 4073:         }
 4074:         if (($end != 0)  &&
 4075:             (($endblock == 0) || ($endblock < $end))) {
 4076:             $endblock = $end;
 4077:         }
 4078:     }
 4079:     return ($startblock,$endblock);
 4080: }
 4081: 
 4082: sub get_blocks {
 4083:     my ($setters,$activity,$cdom,$cnum) = @_;
 4084:     my $startblock = 0;
 4085:     my $endblock = 0;
 4086:     my $course = $cdom.'_'.$cnum;
 4087:     $setters->{$course} = {};
 4088:     $setters->{$course}{'staff'} = [];
 4089:     $setters->{$course}{'times'} = [];
 4090:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4091:     foreach my $record (keys(%records)) {
 4092:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4093:         if ($start <= time && $end >= time) {
 4094:             my ($staff_name,$staff_dom,$title,$blocks) =
 4095:                 &parse_block_record($records{$record});
 4096:             if ($blocks->{$activity} eq 'on') {
 4097:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4098:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4099:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4100:                     $startblock = $start;
 4101:                 }
 4102:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4103:                     $endblock = $end;
 4104:                 }
 4105:             }
 4106:         }
 4107:     }
 4108:     return ($startblock,$endblock);
 4109: }
 4110: 
 4111: sub parse_block_record {
 4112:     my ($record) = @_;
 4113:     my ($setuname,$setudom,$title,$blocks);
 4114:     if (ref($record) eq 'HASH') {
 4115:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4116:         $title = &unescape($record->{'event'});
 4117:         $blocks = $record->{'blocks'};
 4118:     } else {
 4119:         my @data = split(/:/,$record,3);
 4120:         if (scalar(@data) eq 2) {
 4121:             $title = $data[1];
 4122:             ($setuname,$setudom) = split(/@/,$data[0]);
 4123:         } else {
 4124:             ($setuname,$setudom,$title) = @data;
 4125:         }
 4126:         $blocks = { 'com' => 'on' };
 4127:     }
 4128:     return ($setuname,$setudom,$title,$blocks);
 4129: }
 4130: 
 4131: sub blocking_status {
 4132:   my ($activity,$uname,$udom) = @_;
 4133:   my %setters;
 4134: 
 4135:   # check for active blocking
 4136:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4137: 
 4138:   my $blocked = $startblock && $endblock ? 1 : 0;
 4139: 
 4140:   # caller just wants to know whether a block is active
 4141:   if (!wantarray) { return $blocked; }
 4142: 
 4143:   # build a link to a popup window containing the details
 4144:   my $querystring  = "?activity=$activity";
 4145:   # $uname and $udom decide whose portfolio the user is trying to look at
 4146:      $querystring .= "&amp;udom=$udom"      if $udom;
 4147:      $querystring .= "&amp;uname=$uname"    if $uname;
 4148: 
 4149:   my $output .= <<'END_MYBLOCK';
 4150:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4151:         var options = "width=" + w + ",height=" + h + ",";
 4152:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4153:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4154:         var newWin = window.open(url, wdwName, options);
 4155:         newWin.focus();
 4156:     }
 4157: END_MYBLOCK
 4158: 
 4159:   $output = Apache::lonhtmlcommon::scripttag($output);
 4160:   
 4161:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4162:   my $text = mt('Communication Blocked');
 4163: 
 4164:   $output .= <<"END_BLOCK";
 4165: <div class='LC_comblock'>
 4166:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4167:   title='$text'>
 4168:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4169:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4170:   title='$text'>$text</a>
 4171: </div>
 4172: 
 4173: END_BLOCK
 4174: 
 4175:   return ($blocked, $output);
 4176: }
 4177: 
 4178: ###############################################
 4179: 
 4180: sub check_ip_acc {
 4181:     my ($acc)=@_;
 4182:     &Apache::lonxml::debug("acc is $acc");
 4183:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4184:         return 1;
 4185:     }
 4186:     my $allowed=0;
 4187:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4188: 
 4189:     my $name;
 4190:     foreach my $pattern (split(',',$acc)) {
 4191:         $pattern =~ s/^\s*//;
 4192:         $pattern =~ s/\s*$//;
 4193:         if ($pattern =~ /\*$/) {
 4194:             #35.8.*
 4195:             $pattern=~s/\*//;
 4196:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4197:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4198:             #35.8.3.[34-56]
 4199:             my $low=$2;
 4200:             my $high=$3;
 4201:             $pattern=$1;
 4202:             if ($ip =~ /^\Q$pattern\E/) {
 4203:                 my $last=(split(/\./,$ip))[3];
 4204:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4205:             }
 4206:         } elsif ($pattern =~ /^\*/) {
 4207:             #*.msu.edu
 4208:             $pattern=~s/\*//;
 4209:             if (!defined($name)) {
 4210:                 use Socket;
 4211:                 my $netaddr=inet_aton($ip);
 4212:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4213:             }
 4214:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4215:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4216:             #127.0.0.1
 4217:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4218:         } else {
 4219:             #some.name.com
 4220:             if (!defined($name)) {
 4221:                 use Socket;
 4222:                 my $netaddr=inet_aton($ip);
 4223:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4224:             }
 4225:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4226:         }
 4227:         if ($allowed) { last; }
 4228:     }
 4229:     return $allowed;
 4230: }
 4231: 
 4232: ###############################################
 4233: 
 4234: =pod
 4235: 
 4236: =head1 Domain Template Functions
 4237: 
 4238: =over 4
 4239: 
 4240: =item * &determinedomain()
 4241: 
 4242: Inputs: $domain (usually will be undef)
 4243: 
 4244: Returns: Determines which domain should be used for designs
 4245: 
 4246: =cut
 4247: 
 4248: ###############################################
 4249: sub determinedomain {
 4250:     my $domain=shift;
 4251:     if (! $domain) {
 4252:         # Determine domain if we have not been given one
 4253:         $domain = &Apache::lonnet::default_login_domain();
 4254:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4255:         if ($env{'request.role.domain'}) { 
 4256:             $domain=$env{'request.role.domain'}; 
 4257:         }
 4258:     }
 4259:     return $domain;
 4260: }
 4261: ###############################################
 4262: 
 4263: sub devalidate_domconfig_cache {
 4264:     my ($udom)=@_;
 4265:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4266: }
 4267: 
 4268: # ---------------------- Get domain configuration for a domain
 4269: sub get_domainconf {
 4270:     my ($udom) = @_;
 4271:     my $cachetime=1800;
 4272:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4273:     if (defined($cached)) { return %{$result}; }
 4274: 
 4275:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4276: 					     ['login','rolecolors','autoenroll'],$udom);
 4277:     my (%designhash,%legacy);
 4278:     if (keys(%domconfig) > 0) {
 4279:         if (ref($domconfig{'login'}) eq 'HASH') {
 4280:             if (keys(%{$domconfig{'login'}})) {
 4281:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4282:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4283:                         if ($key eq 'loginvia') {
 4284:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4285:                                 my @ids = &Apache::lonnet::current_machine_ids();
 4286:                                 foreach my $hostname (@ids) {
 4287:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4288:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4289:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4290:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4291:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4292: 
 4293:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4294:                                             } else {
 4295:                                                  $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4296:                                             }
 4297:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4298:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4299:                                             }
 4300:                                         }
 4301:                                     }
 4302:                                 }
 4303:                             }
 4304:                         } else {
 4305:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4306:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4307:                                     $domconfig{'login'}{$key}{$img};
 4308:                             }
 4309:                         }
 4310:                     } else {
 4311:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4312:                     }
 4313:                 }
 4314:             } else {
 4315:                 $legacy{'login'} = 1;
 4316:             }
 4317:         } else {
 4318:             $legacy{'login'} = 1;
 4319:         }
 4320:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4321:             if (keys(%{$domconfig{'rolecolors'}})) {
 4322:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4323:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4324:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4325:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4326:                         }
 4327:                     }
 4328:                 }
 4329:             } else {
 4330:                 $legacy{'rolecolors'} = 1;
 4331:             }
 4332:         } else {
 4333:             $legacy{'rolecolors'} = 1;
 4334:         }
 4335:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4336:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4337:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4338:             }
 4339:         }
 4340:         if (keys(%legacy) > 0) {
 4341:             my %legacyhash = &get_legacy_domconf($udom);
 4342:             foreach my $item (keys(%legacyhash)) {
 4343:                 if ($item =~ /^\Q$udom\E\.login/) {
 4344:                     if ($legacy{'login'}) { 
 4345:                         $designhash{$item} = $legacyhash{$item};
 4346:                     }
 4347:                 } else {
 4348:                     if ($legacy{'rolecolors'}) {
 4349:                         $designhash{$item} = $legacyhash{$item};
 4350:                     }
 4351:                 }
 4352:             }
 4353:         }
 4354:     } else {
 4355:         %designhash = &get_legacy_domconf($udom); 
 4356:     }
 4357:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4358: 				  $cachetime);
 4359:     return %designhash;
 4360: }
 4361: 
 4362: sub get_legacy_domconf {
 4363:     my ($udom) = @_;
 4364:     my %legacyhash;
 4365:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4366:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4367:     if (-e $designfile) {
 4368:         if ( open (my $fh,"<$designfile") ) {
 4369:             while (my $line = <$fh>) {
 4370:                 next if ($line =~ /^\#/);
 4371:                 chomp($line);
 4372:                 my ($key,$val)=(split(/\=/,$line));
 4373:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4374:             }
 4375:             close($fh);
 4376:         }
 4377:     }
 4378:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4379:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4380:     }
 4381:     return %legacyhash;
 4382: }
 4383: 
 4384: =pod
 4385: 
 4386: =item * &domainlogo()
 4387: 
 4388: Inputs: $domain (usually will be undef)
 4389: 
 4390: Returns: A link to a domain logo, if the domain logo exists.
 4391: If the domain logo does not exist, a description of the domain.
 4392: 
 4393: =cut
 4394: 
 4395: ###############################################
 4396: sub domainlogo {
 4397:     my $domain = &determinedomain(shift);
 4398:     my %designhash = &get_domainconf($domain);    
 4399:     # See if there is a logo
 4400:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4401:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4402:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4403: 	    if ($imgsrc =~ m{^/res/}) {
 4404: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4405: 		&Apache::lonnet::repcopy($local_name);
 4406: 	    }
 4407: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4408:         } 
 4409:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4410:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4411:         return &Apache::lonnet::domain($domain,'description');
 4412:     } else {
 4413:         return '';
 4414:     }
 4415: }
 4416: ##############################################
 4417: 
 4418: =pod
 4419: 
 4420: =item * &designparm()
 4421: 
 4422: Inputs: $which parameter; $domain (usually will be undef)
 4423: 
 4424: Returns: value of designparamter $which
 4425: 
 4426: =cut
 4427: 
 4428: 
 4429: ##############################################
 4430: sub designparm {
 4431:     my ($which,$domain)=@_;
 4432:     if (exists($env{'environment.color.'.$which})) {
 4433:         return $env{'environment.color.'.$which};
 4434:     }
 4435:     $domain=&determinedomain($domain);
 4436:     my %domdesign = &get_domainconf($domain);
 4437:     my $output;
 4438:     if ($domdesign{$domain.'.'.$which} ne '') {
 4439:         $output = $domdesign{$domain.'.'.$which};
 4440:     } else {
 4441:         $output = $defaultdesign{$which};
 4442:     }
 4443:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4444:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4445:         if ($output =~ m{^/(adm|res)/}) {
 4446:             if ($output =~ m{^/res/}) {
 4447:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4448:                 &Apache::lonnet::repcopy($local_name);
 4449:             }
 4450:             $output = &lonhttpdurl($output);
 4451:         }
 4452:     }
 4453:     return $output;
 4454: }
 4455: 
 4456: ##############################################
 4457: =pod
 4458: 
 4459: =item * &authorspace()
 4460: 
 4461: Inputs: ./.
 4462: 
 4463: Returns: Path to the Construction Space of the current user's
 4464:          accessed author space
 4465:          The author space will be that of the current user
 4466:          when accessing the own author space
 4467:          and that of the co-author/assistent co-author
 4468:          when accessing the co-author's/assistent co-author's
 4469:          space
 4470: 
 4471: =cut
 4472: 
 4473: sub authorspace {
 4474:     my $caname = '';
 4475:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4476:         (undef,$caname) =
 4477:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4478:     } else {
 4479:         $caname = $env{'user.name'};
 4480:     }
 4481:     return '/priv/'.$caname.'/';
 4482: }
 4483: 
 4484: ##############################################
 4485: =pod
 4486: 
 4487: =item * &head_subbox()
 4488: 
 4489: Inputs: $content (contains HTML code with page functions, etc.)
 4490: 
 4491: Returns: HTML div with $content
 4492:          To be included in page header
 4493: 
 4494: =cut
 4495: 
 4496: sub head_subbox {
 4497:     my ($content)=@_;
 4498:     my $output =
 4499:         '<div class="LC_head_subbox">'
 4500:        .$content
 4501:        .'</div>'
 4502: }
 4503: 
 4504: ##############################################
 4505: =pod
 4506: 
 4507: =item * &CSTR_pageheader()
 4508: 
 4509: Inputs: ./.
 4510: 
 4511: Returns: HTML div with CSTR path and recent box
 4512:          To be included on Construction Space pages
 4513: 
 4514: =cut
 4515: 
 4516: sub CSTR_pageheader {
 4517:     # this is for resources; directories have customtitle, and crumbs
 4518:             # and select recent are created in lonpubdir.pm  
 4519:     my ($uname,$thisdisfn)=
 4520:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4521:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4522:     $formaction=~s/\/+/\//g;
 4523: 
 4524:     my $parentpath = '';
 4525:     my $lastitem = '';
 4526:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4527:         $parentpath = $1;
 4528:         $lastitem = $2;
 4529:     } else {
 4530:         $lastitem = $thisdisfn;
 4531:     }
 4532: 
 4533:     my $output =
 4534:          '<div>'
 4535:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4536:         .'<b>'.&mt('Construction Space:').'</b> '
 4537:         .'<form name="dirs" method="post" action="'.$formaction
 4538:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4539:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
 4540: 
 4541:     if ($lastitem) {
 4542:         $output .=
 4543:              '<span class="LC_filename">'
 4544:             .$lastitem
 4545:             .'</span>';
 4546:     }
 4547:     $output .=
 4548:          '<br />'
 4549:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4550:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4551:         .'</form>'
 4552:         .&Apache::lonmenu::constspaceform()
 4553:         .'</div>';
 4554: 
 4555:     return $output;
 4556: }
 4557: 
 4558: ###############################################
 4559: ###############################################
 4560: 
 4561: =pod
 4562: 
 4563: =back
 4564: 
 4565: =head1 HTML Helpers
 4566: 
 4567: =over 4
 4568: 
 4569: =item * &bodytag()
 4570: 
 4571: Returns a uniform header for LON-CAPA web pages.
 4572: 
 4573: Inputs: 
 4574: 
 4575: =over 4
 4576: 
 4577: =item * $title, A title to be displayed on the page.
 4578: 
 4579: =item * $function, the current role (can be undef).
 4580: 
 4581: =item * $addentries, extra parameters for the <body> tag.
 4582: 
 4583: =item * $bodyonly, if defined, only return the <body> tag.
 4584: 
 4585: =item * $domain, if defined, force a given domain.
 4586: 
 4587: =item * $forcereg, if page should register as content page (relevant for 
 4588:             text interface only)
 4589: 
 4590: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4591:                      navigational links
 4592: 
 4593: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4594: 
 4595: =item * $no_inline_link, if true and in remote mode, don't show the 
 4596:          'Switch To Inline Menu' link
 4597: 
 4598: =item * $args, optional argument valid values are
 4599:             no_auto_mt_title -> prevents &mt()ing the title arg
 4600:             inherit_jsmath -> when creating popup window in a page,
 4601:                               should it have jsmath forced on by the
 4602:                               current page
 4603: 
 4604: =back
 4605: 
 4606: Returns: A uniform header for LON-CAPA web pages.  
 4607: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4608: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4609: other decorations will be returned.
 4610: 
 4611: =cut
 4612: 
 4613: sub bodytag {
 4614:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4615:         $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
 4616: 
 4617:     my $public;
 4618:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4619:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4620:         $public = 1;
 4621:     }
 4622:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4623: 
 4624:     $function = &get_users_function() if (!$function);
 4625:     my $img =    &designparm($function.'.img',$domain);
 4626:     my $font =   &designparm($function.'.font',$domain);
 4627:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4628: 
 4629:     my %design = ( 'style'   => 'margin-top: 0',
 4630: 		   'bgcolor' => $pgbg,
 4631: 		   'text'    => $font,
 4632:                    'alink'   => &designparm($function.'.alink',$domain),
 4633: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4634: 		   'link'    => &designparm($function.'.link',$domain),);
 4635:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4636: 
 4637:  # role and realm
 4638:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4639:     if ($role  eq 'ca') {
 4640:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4641:         $realm = &plainname($rname,$rdom);
 4642:     } 
 4643: # realm
 4644:     if ($env{'request.course.id'}) {
 4645:         if ($env{'request.role'} !~ /^cr/) {
 4646:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4647:         }
 4648:         if ($env{'request.course.sec'}) {
 4649:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4650:         }   
 4651: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4652:     } else {
 4653:         $role = &Apache::lonnet::plaintext($role);
 4654:     }
 4655: 
 4656:     if (!$realm) { $realm='&nbsp;'; }
 4657: # Set messages
 4658:     my $messages=&domainlogo($domain);
 4659: 
 4660:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4661: 
 4662: # construct main body tag
 4663:     my $bodytag = "<body $extra_body_attr>".
 4664: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4665: 
 4666:     if ($bodyonly) {
 4667:         return $bodytag;
 4668:     } 
 4669: 
 4670:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4671:     if ($public) {
 4672: 	undef($role);
 4673:     } else {
 4674: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4675:     }
 4676: 
 4677:     my $titleinfo = '<h1>'.$title.'</h1>';
 4678:     #
 4679:     # Extra info if you are the DC
 4680:     my $dc_info = '';
 4681:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4682:                         $env{'course.'.$env{'request.course.id'}.
 4683:                                  '.domain'}.'/'})) {
 4684:         my $cid = $env{'request.course.id'};
 4685:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4686:         $dc_info =~ s/\s+$//;
 4687:     }
 4688: 
 4689:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4690:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4691: 
 4692:     if ($env{'environment.remote'} ne 'on') {
 4693:         # No Remote
 4694:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4695:             return $bodytag;
 4696:         }
 4697: 
 4698:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4699: 
 4700:         #    if ($env{'request.state'} eq 'construct') {
 4701:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4702:         #    }
 4703: 
 4704: 
 4705: 
 4706:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4707:              if ($dc_info) {
 4708:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4709:              }
 4710:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4711:                 <em>$realm</em> $dc_info</div>|;
 4712:             return $bodytag;
 4713:         }
 4714:         if (($env{'request.noversionuri'} =~ m{^/adm/navmaps}) &&
 4715:              ($env{'environment.remotenavmap'} eq 'on')) {
 4716:             return $bodytag;
 4717:         }
 4718: 
 4719:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4720:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4721:         }
 4722: 
 4723:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4724:             Apache::lonmenu::utilityfunctions(), 'start');
 4725: 
 4726:         $bodytag .= Apache::lonmenu::primary_menu();
 4727: 
 4728:         if ($dc_info) {
 4729:             $dc_info = &dc_courseid_toggle($dc_info);
 4730:         }
 4731:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4732: 
 4733:         #don't show menus for public users
 4734:         if (!$public){
 4735:             $bodytag .= Apache::lonmenu::secondary_menu();
 4736:             $bodytag .= Apache::lonmenu::serverform();
 4737:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4738:             if ($env{'request.state'} eq 'construct') {
 4739:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,'',
 4740:                                 $args->{'bread_crumbs'});
 4741:             } elsif ($forcereg) { 
 4742:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4743:             }
 4744:         }else{
 4745:             # this is to seperate menu from content when there's no secondary
 4746:             # menu. Especially needed for public accessible ressources.
 4747:             $bodytag .= '<hr style="clear:both" />';
 4748:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4749:         }
 4750: 
 4751:         return $bodytag;
 4752:     }
 4753: 
 4754: #
 4755: # Top frame rendering, Remote is up
 4756: #
 4757: 
 4758:     my $imgsrc = $img;
 4759:     if ($img =~ /^\/adm/) {
 4760:         $imgsrc = &lonhttpdurl($img);
 4761:     }
 4762:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4763: 
 4764:     # Explicit link to get inline menu
 4765:     my $menu= ($no_inline_link?''
 4766: 	       :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 4767: 
 4768:     if ($dc_info) {
 4769:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 4770:     }
 4771: 
 4772:     unless ($env{'form.inhibitmenu'}) {
 4773:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 4774:                        <ol class="LC_primary_menu LC_right">
 4775:                        <li>$menu</li>
 4776:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 4777:     }
 4778: 
 4779:     return(<<ENDBODY);
 4780: $bodytag
 4781: <table id="LC_title_bar" class="LC_with_remote">
 4782: <tr><td>$upperleft</td>
 4783:     <td>$messages&nbsp;</td>
 4784: </tr>
 4785: <tr><td>$titleinfo $dc_info $menu</td>
 4786: </tr>
 4787: </table>
 4788: ENDBODY
 4789: }
 4790: 
 4791: sub dc_courseid_toggle {
 4792:     my ($dc_info) = @_;
 4793:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 4794:            '<a href="javascript:showCourseID();">'.
 4795:            &mt('(More ...)').'</a></span>'.
 4796:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4797: }
 4798: 
 4799: sub make_attr_string {
 4800:     my ($register,$attr_ref) = @_;
 4801: 
 4802:     if ($attr_ref && !ref($attr_ref)) {
 4803: 	die("addentries Must be a hash ref ".
 4804: 	    join(':',caller(1))." ".
 4805: 	    join(':',caller(0))." ");
 4806:     }
 4807: 
 4808:     if ($register) {
 4809: 	my ($on_load,$on_unload);
 4810: 	foreach my $key (keys(%{$attr_ref})) {
 4811: 	    if      (lc($key) eq 'onload') {
 4812: 		$on_load.=$attr_ref->{$key}.';';
 4813: 		delete($attr_ref->{$key});
 4814: 
 4815: 	    } elsif (lc($key) eq 'onunload') {
 4816: 		$on_unload.=$attr_ref->{$key}.';';
 4817: 		delete($attr_ref->{$key});
 4818: 	    }
 4819: 	}
 4820: 	$attr_ref->{'onload'}  =
 4821: 	    &Apache::lonmenu::loadevents().  $on_load;
 4822: 	$attr_ref->{'onunload'}=
 4823: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4824:     }
 4825: 
 4826: # Accessibility font enhance
 4827:     if ($env{'browser.fontenhance'} eq 'on') {
 4828: 	my $style;
 4829: 	foreach my $key (keys(%{$attr_ref})) {
 4830: 	    if (lc($key) eq 'style') {
 4831: 		$style.=$attr_ref->{$key}.';';
 4832: 		delete($attr_ref->{$key});
 4833: 	    }
 4834: 	}
 4835: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4836:     }
 4837: 
 4838:     my $attr_string;
 4839:     foreach my $attr (keys(%$attr_ref)) {
 4840: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4841:     }
 4842:     return $attr_string;
 4843: }
 4844: 
 4845: 
 4846: ###############################################
 4847: ###############################################
 4848: 
 4849: =pod
 4850: 
 4851: =item * &endbodytag()
 4852: 
 4853: Returns a uniform footer for LON-CAPA web pages.
 4854: 
 4855: Inputs: 1 - optional reference to an args hash
 4856: If in the hash, key for noredirectlink has a value which evaluates to true,
 4857: a 'Continue' link is not displayed if the page contains an
 4858: internal redirect in the <head></head> section,
 4859: i.e., $env{'internal.head.redirect'} exists   
 4860: 
 4861: =cut
 4862: 
 4863: sub endbodytag {
 4864:     my ($args) = @_;
 4865:     my $endbodytag='</body>';
 4866:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4867:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4868:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4869: 	    $endbodytag=
 4870: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4871: 	        &mt('Continue').'</a>'.
 4872: 	        $endbodytag;
 4873:         }
 4874:     }
 4875:     return $endbodytag;
 4876: }
 4877: 
 4878: =pod
 4879: 
 4880: =item * &standard_css()
 4881: 
 4882: Returns a style sheet
 4883: 
 4884: Inputs: (all optional)
 4885:             domain         -> force to color decorate a page for a specific
 4886:                                domain
 4887:             function       -> force usage of a specific rolish color scheme
 4888:             bgcolor        -> override the default page bgcolor
 4889: 
 4890: =cut
 4891: 
 4892: sub standard_css {
 4893:     my ($function,$domain,$bgcolor) = @_;
 4894:     $function  = &get_users_function() if (!$function);
 4895:     my $img    = &designparm($function.'.img',   $domain);
 4896:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4897:     my $font   = &designparm($function.'.font',  $domain);
 4898:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4899: #second colour for later usage
 4900:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4901:     my $pgbg_or_bgcolor =
 4902: 	         $bgcolor ||
 4903: 	         &designparm($function.'.pgbg',  $domain);
 4904:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4905:     my $alink  = &designparm($function.'.alink', $domain);
 4906:     my $vlink  = &designparm($function.'.vlink', $domain);
 4907:     my $link   = &designparm($function.'.link',  $domain);
 4908: 
 4909:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4910:     my $mono                 = 'monospace';
 4911:     my $data_table_head      = $sidebg;
 4912:     my $data_table_light     = '#FAFAFA';
 4913:     my $data_table_dark      = '#F0F0F0';
 4914:     my $data_table_darker    = '#CCCCCC';
 4915:     my $data_table_highlight = '#FFFF00';
 4916:     my $mail_new             = '#FFBB77';
 4917:     my $mail_new_hover       = '#DD9955';
 4918:     my $mail_read            = '#BBBB77';
 4919:     my $mail_read_hover      = '#999944';
 4920:     my $mail_replied         = '#AAAA88';
 4921:     my $mail_replied_hover   = '#888855';
 4922:     my $mail_other           = '#99BBBB';
 4923:     my $mail_other_hover     = '#669999';
 4924:     my $table_header         = '#DDDDDD';
 4925:     my $feedback_link_bg     = '#BBBBBB';
 4926:     my $lg_border_color      = '#C8C8C8';
 4927:     my $button_hover         = '#BF2317';
 4928: 
 4929:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4930:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4931:                                              : '0 3px 0 4px';
 4932: 
 4933:     return <<END;
 4934: 
 4935: /* needed for iframe to allow 100% height in FF */
 4936: body, html { 
 4937:     margin: 0;
 4938:     padding: 0 0.5%;
 4939:     height: 99%; /* to avoid scrollbars */
 4940: }
 4941: 
 4942: body {
 4943:   font-family: $sans;
 4944:   line-height:130%;
 4945:   font-size:0.83em;
 4946:   color:$font;
 4947: }
 4948: 
 4949: a:focus,
 4950: a:focus img {
 4951:   color: red;
 4952:   background: yellow;
 4953: }
 4954: 
 4955: form, .inline {
 4956:   display: inline;
 4957: }
 4958: 
 4959: .LC_right {
 4960:   text-align:right;
 4961: }
 4962: 
 4963: .LC_middle {
 4964:   vertical-align:middle;
 4965: }
 4966: 
 4967: .LC_400Box {
 4968:   width:400px;
 4969: }
 4970: 
 4971: .LC_iframecontainer {
 4972:     width: 98%;
 4973:     margin: 0;
 4974:     position: fixed;
 4975:     top: 8.5em;
 4976:     bottom: 0;
 4977: }
 4978: 
 4979: .LC_iframecontainer iframe{
 4980:     border: none;
 4981:     width: 100%;
 4982:     height: 100%;
 4983: }
 4984: 
 4985: .LC_filename {
 4986:   font-family: $mono;
 4987:   white-space:pre;
 4988:   font-size: 120%;
 4989: }
 4990: 
 4991: .LC_fileicon {
 4992:   border: none;
 4993:   height: 1.3em;
 4994:   vertical-align: text-bottom;
 4995:   margin-right: 0.3em;
 4996:   text-decoration:none;
 4997: }
 4998: 
 4999: .LC_error {
 5000:   color: red;
 5001:   font-size: larger;
 5002: }
 5003: 
 5004: .LC_warning,
 5005: .LC_diff_removed {
 5006:   color: red;
 5007: }
 5008: 
 5009: .LC_info,
 5010: .LC_success,
 5011: .LC_diff_added {
 5012:   color: green;
 5013: }
 5014: 
 5015: div.LC_confirm_box {
 5016:   background-color: #FAFAFA;
 5017:   border: 1px solid $lg_border_color;
 5018:   margin-right: 0;
 5019:   padding: 5px;
 5020: }
 5021: 
 5022: div.LC_confirm_box .LC_error img,
 5023: div.LC_confirm_box .LC_success img {
 5024:   vertical-align: middle;
 5025: }
 5026: 
 5027: .LC_icon {
 5028:   border: none;
 5029:   vertical-align: middle;
 5030: }
 5031: 
 5032: .LC_docs_spacer {
 5033:   width: 25px;
 5034:   height: 1px;
 5035:   border: none;
 5036: }
 5037: 
 5038: .LC_internal_info {
 5039:   color: #999999;
 5040: }
 5041: 
 5042: .LC_discussion {
 5043:   background: $tabbg;
 5044:   border: 1px solid black;
 5045:   margin: 2px;
 5046: }
 5047: 
 5048: .LC_disc_action_links_bar {
 5049:   background: $tabbg;
 5050:   border: none;
 5051:   margin: 4px;
 5052: }
 5053: 
 5054: .LC_disc_action_left {
 5055:   text-align: left;
 5056: }
 5057: 
 5058: .LC_disc_action_right {
 5059:   text-align: right;
 5060: }
 5061: 
 5062: .LC_disc_new_item {
 5063:   background: white;
 5064:   border: 2px solid red;
 5065:   margin: 2px;
 5066: }
 5067: 
 5068: .LC_disc_old_item {
 5069:   background: white;
 5070:   border: 1px solid black;
 5071:   margin: 2px;
 5072: }
 5073: 
 5074: table.LC_pastsubmission {
 5075:   border: 1px solid black;
 5076:   margin: 2px;
 5077: }
 5078: 
 5079: table#LC_menubuttons {
 5080:   width: 100%;
 5081:   background: $pgbg;
 5082:   border: 2px;
 5083:   border-collapse: separate;
 5084:   padding: 0;
 5085: }
 5086: 
 5087: table#LC_title_bar a {
 5088:   color: $fontmenu;
 5089: }
 5090: 
 5091: table#LC_title_bar {
 5092:   clear: both;
 5093:   display: none;
 5094: }
 5095: 
 5096: table#LC_title_bar,
 5097: table.LC_breadcrumbs, /* obsolete? */
 5098: table#LC_title_bar.LC_with_remote {
 5099:   width: 100%;
 5100:   border-color: $pgbg;
 5101:   border-style: solid;
 5102:   border-width: $border;
 5103:   background: $pgbg;
 5104:   color: $fontmenu;
 5105:   border-collapse: collapse;
 5106:   padding: 0;
 5107:   margin: 0;
 5108: }
 5109: 
 5110: ul.LC_breadcrumb_tools_outerlist {
 5111:     margin: 0;
 5112:     padding: 0;
 5113:     position: relative;
 5114:     list-style: none;
 5115: }
 5116: ul.LC_breadcrumb_tools_outerlist li {
 5117:     display: inline;
 5118: }
 5119: 
 5120: .LC_breadcrumb_tools_navigation {
 5121:     padding: 0;
 5122:     margin: 0;
 5123:     float: left;
 5124: }
 5125: .LC_breadcrumb_tools_tools {
 5126:     padding: 0;
 5127:     margin: 0;
 5128:     float: right;
 5129: }
 5130: 
 5131: table#LC_title_bar td {
 5132:   background: $tabbg;
 5133: }
 5134: 
 5135: table#LC_menubuttons img {
 5136:   border: none;
 5137: }
 5138: 
 5139: .LC_breadcrumbs_component {
 5140:   float: right;
 5141:   margin: 0 1em;
 5142: }
 5143: .LC_breadcrumbs_component img {
 5144:   vertical-align: middle;
 5145: }
 5146: 
 5147: td.LC_table_cell_checkbox {
 5148:   text-align: center;
 5149: }
 5150: 
 5151: .LC_fontsize_small {
 5152:   font-size: 70%;
 5153: }
 5154: 
 5155: #LC_breadcrumbs {
 5156:   clear:both;
 5157:   background: $sidebg;
 5158:   border-bottom: 1px solid $lg_border_color;
 5159:   line-height: 2.5em;
 5160:   overflow: hidden;
 5161:   margin: 0;
 5162:   padding: 0;
 5163:   text-align: left;
 5164: }
 5165: 
 5166: /* Preliminary fix to hide breadcrumbs inside remote control window */
 5167: #LC_remote #LC_breadcrumbs {
 5168:   display:none;
 5169: }
 5170: 
 5171: .LC_head_subbox {
 5172:   clear:both;
 5173:   background: #F8F8F8; /* $sidebg; */
 5174:   border: 1px solid $sidebg;
 5175:   margin: 0 0 10px 0;      
 5176:   padding: 3px;
 5177:   text-align: left;
 5178: }
 5179: 
 5180: .LC_fontsize_medium {
 5181:   font-size: 85%;
 5182: }
 5183: 
 5184: .LC_fontsize_large {
 5185:   font-size: 120%;
 5186: }
 5187: 
 5188: .LC_menubuttons_inline_text {
 5189:   color: $font;
 5190:   font-size: 90%;
 5191:   padding-left:3px;
 5192: }
 5193: 
 5194: .LC_menubuttons_inline_text img{
 5195:   vertical-align: middle;
 5196: }
 5197: 
 5198: li.LC_menubuttons_inline_text img,a {
 5199:   cursor:pointer;
 5200:   text-decoration: none;
 5201: }
 5202: 
 5203: .LC_menubuttons_link {
 5204:   text-decoration: none;
 5205: }
 5206: 
 5207: .LC_menubuttons_category {
 5208:   color: $font;
 5209:   background: $pgbg;
 5210:   font-size: larger;
 5211:   font-weight: bold;
 5212: }
 5213: 
 5214: td.LC_menubuttons_text {
 5215:   color: $font;
 5216: }
 5217: 
 5218: .LC_current_location {
 5219:   background: $tabbg;
 5220: }
 5221: 
 5222: table.LC_data_table {
 5223:   border: 1px solid #000000;
 5224:   border-collapse: separate;
 5225:   border-spacing: 1px;
 5226:   background: $pgbg;
 5227: }
 5228: 
 5229: .LC_data_table_dense {
 5230:   font-size: small;
 5231: }
 5232: 
 5233: table.LC_nested_outer {
 5234:   border: 1px solid #000000;
 5235:   border-collapse: collapse;
 5236:   border-spacing: 0;
 5237:   width: 100%;
 5238: }
 5239: 
 5240: table.LC_innerpickbox,
 5241: table.LC_nested {
 5242:   border: none;
 5243:   border-collapse: collapse;
 5244:   border-spacing: 0;
 5245:   width: 100%;
 5246: }
 5247: 
 5248: .ui-accordion,
 5249: .ui-accordion table.LC_data_table,
 5250: .ui-accordion table.LC_nested_outer{
 5251:   border: 0px;
 5252:   border-spacing: 0px;
 5253:   margin: 3px;
 5254: }
 5255: 
 5256: table.LC_data_table tr th,
 5257: table.LC_calendar tr th,
 5258: table.LC_prior_tries tr th,
 5259: table.LC_innerpickbox tr th {
 5260:   font-weight: bold;
 5261:   background-color: $data_table_head;
 5262:   color:$fontmenu;
 5263:   font-size:90%;
 5264: }
 5265: 
 5266: table.LC_innerpickbox tr th,
 5267: table.LC_innerpickbox tr td {
 5268:   vertical-align: top;
 5269: }
 5270: 
 5271: table.LC_data_table tr.LC_info_row > td {
 5272:   background-color: #CCCCCC;
 5273:   font-weight: bold;
 5274:   text-align: left;
 5275: }
 5276: 
 5277: table.LC_data_table tr.LC_odd_row > td {
 5278:   background-color: $data_table_light;
 5279:   padding: 2px;
 5280:   vertical-align: top;
 5281: }
 5282: 
 5283: table.LC_pick_box tr > td.LC_odd_row {
 5284:   background-color: $data_table_light;
 5285:   vertical-align: top;
 5286: }
 5287: 
 5288: table.LC_data_table tr.LC_even_row > td {
 5289:   background-color: $data_table_dark;
 5290:   padding: 2px;
 5291:   vertical-align: top;
 5292: }
 5293: 
 5294: table.LC_pick_box tr > td.LC_even_row {
 5295:   background-color: $data_table_dark;
 5296:   vertical-align: top;
 5297: }
 5298: 
 5299: table.LC_data_table tr.LC_data_table_highlight td {
 5300:   background-color: $data_table_darker;
 5301: }
 5302: 
 5303: table.LC_data_table tr td.LC_leftcol_header {
 5304:   background-color: $data_table_head;
 5305:   font-weight: bold;
 5306: }
 5307: 
 5308: table.LC_data_table tr.LC_empty_row td,
 5309: table.LC_nested tr.LC_empty_row td {
 5310:   font-weight: bold;
 5311:   font-style: italic;
 5312:   text-align: center;
 5313:   padding: 8px;
 5314: }
 5315: 
 5316: table.LC_data_table tr.LC_empty_row td {
 5317:   background-color: $sidebg;
 5318: }
 5319: 
 5320: table.LC_nested tr.LC_empty_row td {
 5321:   background-color: #FFFFFF;
 5322: }
 5323: 
 5324: table.LC_caption {
 5325: }
 5326: 
 5327: table.LC_nested tr.LC_empty_row td {
 5328:   padding: 4ex
 5329: }
 5330: 
 5331: table.LC_nested_outer tr th {
 5332:   font-weight: bold;
 5333:   color:$fontmenu;
 5334:   background-color: $data_table_head;
 5335:   font-size: small;
 5336:   border-bottom: 1px solid #000000;
 5337: }
 5338: 
 5339: table.LC_nested_outer tr td.LC_subheader {
 5340:   background-color: $data_table_head;
 5341:   font-weight: bold;
 5342:   font-size: small;
 5343:   border-bottom: 1px solid #000000;
 5344:   text-align: right;
 5345: }
 5346: 
 5347: table.LC_nested tr.LC_info_row td {
 5348:   background-color: #CCCCCC;
 5349:   font-weight: bold;
 5350:   font-size: small;
 5351:   text-align: center;
 5352: }
 5353: 
 5354: table.LC_nested tr.LC_info_row td.LC_left_item,
 5355: table.LC_nested_outer tr th.LC_left_item {
 5356:   text-align: left;
 5357: }
 5358: 
 5359: table.LC_nested td {
 5360:   background-color: #FFFFFF;
 5361:   font-size: small;
 5362: }
 5363: 
 5364: table.LC_nested_outer tr th.LC_right_item,
 5365: table.LC_nested tr.LC_info_row td.LC_right_item,
 5366: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5367: table.LC_nested tr td.LC_right_item {
 5368:   text-align: right;
 5369: }
 5370: 
 5371: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_left_item,
 5372: .ui-accordion table.LC_nested tr.LC_even_row td.LC_left_item {
 5373:   text-align: right;
 5374:   width: 40%;
 5375:   padding-right:10px;
 5376:   vertical-align: top;
 5377:   padding: 5px;
 5378: }
 5379: 
 5380: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_right_item,
 5381: .ui-accordion table.LC_nested tr.LC_even_row td.LC_right_item {
 5382:   text-align: left;
 5383:   width: 60%;
 5384:   padding: 2px 4px;
 5385: }
 5386: 
 5387: table.LC_nested tr.LC_odd_row td {
 5388:   background-color: #EEEEEE;
 5389: }
 5390: 
 5391: table.LC_createuser {
 5392: }
 5393: 
 5394: table.LC_createuser tr.LC_section_row td {
 5395:   font-size: small;
 5396: }
 5397: 
 5398: table.LC_createuser tr.LC_info_row td  {
 5399:   background-color: #CCCCCC;
 5400:   font-weight: bold;
 5401:   text-align: center;
 5402: }
 5403: 
 5404: table.LC_calendar {
 5405:   border: 1px solid #000000;
 5406:   border-collapse: collapse;
 5407:   width: 98%;
 5408: }
 5409: 
 5410: table.LC_calendar_pickdate {
 5411:   font-size: xx-small;
 5412: }
 5413: 
 5414: table.LC_calendar tr td {
 5415:   border: 1px solid #000000;
 5416:   vertical-align: top;
 5417:   width: 14%;
 5418: }
 5419: 
 5420: table.LC_calendar tr td.LC_calendar_day_empty {
 5421:   background-color: $data_table_dark;
 5422: }
 5423: 
 5424: table.LC_calendar tr td.LC_calendar_day_current {
 5425:   background-color: $data_table_highlight;
 5426: }
 5427: 
 5428: table.LC_data_table tr td.LC_mail_new {
 5429:   background-color: $mail_new;
 5430: }
 5431: 
 5432: table.LC_data_table tr.LC_mail_new:hover {
 5433:   background-color: $mail_new_hover;
 5434: }
 5435: 
 5436: table.LC_data_table tr td.LC_mail_read {
 5437:   background-color: $mail_read;
 5438: }
 5439: 
 5440: /*
 5441: table.LC_data_table tr.LC_mail_read:hover {
 5442:   background-color: $mail_read_hover;
 5443: }
 5444: */
 5445: 
 5446: table.LC_data_table tr td.LC_mail_replied {
 5447:   background-color: $mail_replied;
 5448: }
 5449: 
 5450: /*
 5451: table.LC_data_table tr.LC_mail_replied:hover {
 5452:   background-color: $mail_replied_hover;
 5453: }
 5454: */
 5455: 
 5456: table.LC_data_table tr td.LC_mail_other {
 5457:   background-color: $mail_other;
 5458: }
 5459: 
 5460: /*
 5461: table.LC_data_table tr.LC_mail_other:hover {
 5462:   background-color: $mail_other_hover;
 5463: }
 5464: */
 5465: 
 5466: table.LC_data_table tr > td.LC_browser_file,
 5467: table.LC_data_table tr > td.LC_browser_file_published {
 5468:   background: #AAEE77;
 5469: }
 5470: 
 5471: table.LC_data_table tr > td.LC_browser_file_locked,
 5472: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5473:   background: #FFAA99;
 5474: }
 5475: 
 5476: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5477:   background: #888888;
 5478: }
 5479: 
 5480: table.LC_data_table tr > td.LC_browser_file_modified,
 5481: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5482:   background: #F8F866;
 5483: }
 5484: 
 5485: table.LC_data_table tr.LC_browser_folder > td {
 5486:   background: #E0E8FF;
 5487: }
 5488: 
 5489: table.LC_data_table tr > td.LC_roles_is {
 5490:   /* background: #77FF77; */
 5491: }
 5492: 
 5493: table.LC_data_table tr > td.LC_roles_future {
 5494:   border-right: 8px solid #FFFF77;
 5495: }
 5496: 
 5497: table.LC_data_table tr > td.LC_roles_will {
 5498:   border-right: 8px solid #FFAA77;
 5499: }
 5500: 
 5501: table.LC_data_table tr > td.LC_roles_expired {
 5502:   border-right: 8px solid #FF7777;
 5503: }
 5504: 
 5505: table.LC_data_table tr > td.LC_roles_will_not {
 5506:   border-right: 8px solid #AAFF77;
 5507: }
 5508: 
 5509: table.LC_data_table tr > td.LC_roles_selected {
 5510:   border-right: 8px solid #11CC55;
 5511: }
 5512: 
 5513: span.LC_current_location {
 5514:   font-size:larger;
 5515:   background: $pgbg;
 5516: }
 5517: 
 5518: span.LC_parm_menu_item {
 5519:   font-size: larger;
 5520: }
 5521: 
 5522: span.LC_parm_scope_all {
 5523:   color: red;
 5524: }
 5525: 
 5526: span.LC_parm_scope_folder {
 5527:   color: green;
 5528: }
 5529: 
 5530: span.LC_parm_scope_resource {
 5531:   color: orange;
 5532: }
 5533: 
 5534: span.LC_parm_part {
 5535:   color: blue;
 5536: }
 5537: 
 5538: span.LC_parm_folder,
 5539: span.LC_parm_symb {
 5540:   font-size: x-small;
 5541:   font-family: $mono;
 5542:   color: #AAAAAA;
 5543: }
 5544: 
 5545: ul.LC_parm_parmlist li {
 5546:   display: inline-block;
 5547:   padding: 0.3em 0.8em;
 5548:   vertical-align: top;
 5549:   width: 150px;
 5550:   border-top:1px solid $lg_border_color;
 5551: }
 5552: 
 5553: td.LC_parm_overview_level_menu,
 5554: td.LC_parm_overview_map_menu,
 5555: td.LC_parm_overview_parm_selectors,
 5556: td.LC_parm_overview_restrictions  {
 5557:   border: 1px solid black;
 5558:   border-collapse: collapse;
 5559: }
 5560: 
 5561: table.LC_parm_overview_restrictions td {
 5562:   border-width: 1px 4px 1px 4px;
 5563:   border-style: solid;
 5564:   border-color: $pgbg;
 5565:   text-align: center;
 5566: }
 5567: 
 5568: table.LC_parm_overview_restrictions th {
 5569:   background: $tabbg;
 5570:   border-width: 1px 4px 1px 4px;
 5571:   border-style: solid;
 5572:   border-color: $pgbg;
 5573: }
 5574: 
 5575: table#LC_helpmenu {
 5576:   border: none;
 5577:   height: 55px;
 5578:   border-spacing: 0;
 5579: }
 5580: 
 5581: table#LC_helpmenu fieldset legend {
 5582:   font-size: larger;
 5583: }
 5584: 
 5585: table#LC_helpmenu_links {
 5586:   width: 100%;
 5587:   border: 1px solid black;
 5588:   background: $pgbg;
 5589:   padding: 0;
 5590:   border-spacing: 1px;
 5591: }
 5592: 
 5593: table#LC_helpmenu_links tr td {
 5594:   padding: 1px;
 5595:   background: $tabbg;
 5596:   text-align: center;
 5597:   font-weight: bold;
 5598: }
 5599: 
 5600: table#LC_helpmenu_links a:link,
 5601: table#LC_helpmenu_links a:visited,
 5602: table#LC_helpmenu_links a:active {
 5603:   text-decoration: none;
 5604:   color: $font;
 5605: }
 5606: 
 5607: table#LC_helpmenu_links a:hover {
 5608:   text-decoration: underline;
 5609:   color: $vlink;
 5610: }
 5611: 
 5612: .LC_chrt_popup_exists {
 5613:   border: 1px solid #339933;
 5614:   margin: -1px;
 5615: }
 5616: 
 5617: .LC_chrt_popup_up {
 5618:   border: 1px solid yellow;
 5619:   margin: -1px;
 5620: }
 5621: 
 5622: .LC_chrt_popup {
 5623:   border: 1px solid #8888FF;
 5624:   background: #CCCCFF;
 5625: }
 5626: 
 5627: table.LC_pick_box {
 5628:   border-collapse: separate;
 5629:   background: white;
 5630:   border: 1px solid black;
 5631:   border-spacing: 1px;
 5632: }
 5633: 
 5634: table.LC_pick_box td.LC_pick_box_title {
 5635:   background: $sidebg;
 5636:   font-weight: bold;
 5637:   text-align: left;
 5638:   vertical-align: top;
 5639:   width: 184px;
 5640:   padding: 8px;
 5641: }
 5642: 
 5643: table.LC_pick_box td.LC_pick_box_value {
 5644:   text-align: left;
 5645:   padding: 8px;
 5646: }
 5647: 
 5648: table.LC_pick_box td.LC_pick_box_select {
 5649:   text-align: left;
 5650:   padding: 8px;
 5651: }
 5652: 
 5653: table.LC_pick_box td.LC_pick_box_separator {
 5654:   padding: 0;
 5655:   height: 1px;
 5656:   background: black;
 5657: }
 5658: 
 5659: table.LC_pick_box td.LC_pick_box_submit {
 5660:   text-align: right;
 5661: }
 5662: 
 5663: table.LC_pick_box td.LC_evenrow_value {
 5664:   text-align: left;
 5665:   padding: 8px;
 5666:   background-color: $data_table_light;
 5667: }
 5668: 
 5669: table.LC_pick_box td.LC_oddrow_value {
 5670:   text-align: left;
 5671:   padding: 8px;
 5672:   background-color: $data_table_light;
 5673: }
 5674: 
 5675: span.LC_helpform_receipt_cat {
 5676:   font-weight: bold;
 5677: }
 5678: 
 5679: table.LC_group_priv_box {
 5680:   background: white;
 5681:   border: 1px solid black;
 5682:   border-spacing: 1px;
 5683: }
 5684: 
 5685: table.LC_group_priv_box td.LC_pick_box_title {
 5686:   background: $tabbg;
 5687:   font-weight: bold;
 5688:   text-align: right;
 5689:   width: 184px;
 5690: }
 5691: 
 5692: table.LC_group_priv_box td.LC_groups_fixed {
 5693:   background: $data_table_light;
 5694:   text-align: center;
 5695: }
 5696: 
 5697: table.LC_group_priv_box td.LC_groups_optional {
 5698:   background: $data_table_dark;
 5699:   text-align: center;
 5700: }
 5701: 
 5702: table.LC_group_priv_box td.LC_groups_functionality {
 5703:   background: $data_table_darker;
 5704:   text-align: center;
 5705:   font-weight: bold;
 5706: }
 5707: 
 5708: table.LC_group_priv td {
 5709:   text-align: left;
 5710:   padding: 0;
 5711: }
 5712: 
 5713: table.LC_notify_front_page {
 5714:   background: white;
 5715:   border: 1px solid black;
 5716:   padding: 8px;
 5717: }
 5718: 
 5719: table.LC_notify_front_page td {
 5720:   padding: 8px;
 5721: }
 5722: 
 5723: .LC_navbuttons {
 5724:   margin: 2ex 0ex 2ex 0ex;
 5725: }
 5726: 
 5727: .LC_topic_bar {
 5728:   font-weight: bold;
 5729:   background: $tabbg;
 5730:   margin: 1em 0em 1em 2em;
 5731:   padding: 3px;
 5732:   font-size: 1.2em;
 5733: }
 5734: 
 5735: .LC_topic_bar span {
 5736:   left: 0.5em;
 5737:   position: absolute;
 5738:   vertical-align: middle;
 5739:   font-size: 1.2em;
 5740: }
 5741: 
 5742: table.LC_course_group_status {
 5743:   margin: 20px;
 5744: }
 5745: 
 5746: table.LC_status_selector td {
 5747:   vertical-align: top;
 5748:   text-align: center;
 5749:   padding: 4px;
 5750: }
 5751: 
 5752: div.LC_feedback_link {
 5753:   clear: both;
 5754:   background: $sidebg;
 5755:   width: 100%;
 5756:   padding-bottom: 10px;
 5757:   border: 1px $tabbg solid;
 5758:   height: 22px;
 5759:   line-height: 22px;
 5760:   padding-top: 5px;
 5761: }
 5762: 
 5763: div.LC_feedback_link img {
 5764:   height: 22px;
 5765:   vertical-align:middle;
 5766: }
 5767: 
 5768: div.LC_feedback_link a {
 5769:   text-decoration: none;
 5770: }
 5771: 
 5772: div.LC_comblock {
 5773:   display:inline;
 5774:   color:$font;
 5775:   font-size:90%;
 5776: }
 5777: 
 5778: div.LC_feedback_link div.LC_comblock {
 5779:   padding-left:5px;
 5780: }
 5781: 
 5782: div.LC_feedback_link div.LC_comblock a {
 5783:   color:$font;
 5784: }
 5785: 
 5786: span.LC_feedback_link {
 5787:   /* background: $feedback_link_bg; */
 5788:   font-size: larger;
 5789: }
 5790: 
 5791: span.LC_message_link {
 5792:   /* background: $feedback_link_bg; */
 5793:   font-size: larger;
 5794:   position: absolute;
 5795:   right: 1em;
 5796: }
 5797: 
 5798: table.LC_prior_tries {
 5799:   border: 1px solid #000000;
 5800:   border-collapse: separate;
 5801:   border-spacing: 1px;
 5802: }
 5803: 
 5804: table.LC_prior_tries td {
 5805:   padding: 2px;
 5806: }
 5807: 
 5808: .LC_answer_correct {
 5809:   background: lightgreen;
 5810:   color: darkgreen;
 5811:   padding: 6px;
 5812: }
 5813: 
 5814: .LC_answer_charged_try {
 5815:   background: #FFAAAA;
 5816:   color: darkred;
 5817:   padding: 6px;
 5818: }
 5819: 
 5820: .LC_answer_not_charged_try,
 5821: .LC_answer_no_grade,
 5822: .LC_answer_late {
 5823:   background: lightyellow;
 5824:   color: black;
 5825:   padding: 6px;
 5826: }
 5827: 
 5828: .LC_answer_previous {
 5829:   background: lightblue;
 5830:   color: darkblue;
 5831:   padding: 6px;
 5832: }
 5833: 
 5834: .LC_answer_no_message {
 5835:   background: #FFFFFF;
 5836:   color: black;
 5837:   padding: 6px;
 5838: }
 5839: 
 5840: .LC_answer_unknown {
 5841:   background: orange;
 5842:   color: black;
 5843:   padding: 6px;
 5844: }
 5845: 
 5846: span.LC_prior_numerical,
 5847: span.LC_prior_string,
 5848: span.LC_prior_custom,
 5849: span.LC_prior_reaction,
 5850: span.LC_prior_math {
 5851:   font-family: $mono;
 5852:   white-space: pre;
 5853: }
 5854: 
 5855: span.LC_prior_string {
 5856:   font-family: $mono;
 5857:   white-space: pre;
 5858: }
 5859: 
 5860: table.LC_prior_option {
 5861:   width: 100%;
 5862:   border-collapse: collapse;
 5863: }
 5864: 
 5865: table.LC_prior_rank,
 5866: table.LC_prior_match {
 5867:   border-collapse: collapse;
 5868: }
 5869: 
 5870: table.LC_prior_option tr td,
 5871: table.LC_prior_rank tr td,
 5872: table.LC_prior_match tr td {
 5873:   border: 1px solid #000000;
 5874: }
 5875: 
 5876: .LC_nobreak {
 5877:   white-space: nowrap;
 5878: }
 5879: 
 5880: span.LC_cusr_emph {
 5881:   font-style: italic;
 5882: }
 5883: 
 5884: span.LC_cusr_subheading {
 5885:   font-weight: normal;
 5886:   font-size: 85%;
 5887: }
 5888: 
 5889: div.LC_docs_entry_move {
 5890:   border: 1px solid #BBBBBB;
 5891:   background: #DDDDDD;
 5892:   width: 22px;
 5893:   padding: 1px;
 5894:   margin: 0;
 5895: }
 5896: 
 5897: table.LC_data_table tr > td.LC_docs_entry_commands,
 5898: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5899:   background: #DDDDDD;
 5900:   font-size: x-small;
 5901: }
 5902: 
 5903: .LC_docs_entry_parameter {
 5904:   white-space: nowrap;
 5905: }
 5906: 
 5907: .LC_docs_copy {
 5908:   color: #000099;
 5909: }
 5910: 
 5911: .LC_docs_cut {
 5912:   color: #550044;
 5913: }
 5914: 
 5915: .LC_docs_rename {
 5916:   color: #009900;
 5917: }
 5918: 
 5919: .LC_docs_remove {
 5920:   color: #990000;
 5921: }
 5922: 
 5923: .LC_docs_reinit_warn,
 5924: .LC_docs_ext_edit {
 5925:   font-size: x-small;
 5926: }
 5927: 
 5928: table.LC_docs_adddocs td,
 5929: table.LC_docs_adddocs th {
 5930:   border: 1px solid #BBBBBB;
 5931:   padding: 4px;
 5932:   background: #DDDDDD;
 5933: }
 5934: 
 5935: table.LC_sty_begin {
 5936:   background: #BBFFBB;
 5937: }
 5938: 
 5939: table.LC_sty_end {
 5940:   background: #FFBBBB;
 5941: }
 5942: 
 5943: table.LC_double_column {
 5944:   border-width: 0;
 5945:   border-collapse: collapse;
 5946:   width: 100%;
 5947:   padding: 2px;
 5948: }
 5949: 
 5950: table.LC_double_column tr td.LC_left_col {
 5951:   top: 2px;
 5952:   left: 2px;
 5953:   width: 47%;
 5954:   vertical-align: top;
 5955: }
 5956: 
 5957: table.LC_double_column tr td.LC_right_col {
 5958:   top: 2px;
 5959:   right: 2px;
 5960:   width: 47%;
 5961:   vertical-align: top;
 5962: }
 5963: 
 5964: div.LC_left_float {
 5965:   float: left;
 5966:   padding-right: 5%;
 5967:   padding-bottom: 4px;
 5968: }
 5969: 
 5970: div.LC_clear_float_header {
 5971:   padding-bottom: 2px;
 5972: }
 5973: 
 5974: div.LC_clear_float_footer {
 5975:   padding-top: 10px;
 5976:   clear: both;
 5977: }
 5978: 
 5979: div.LC_grade_show_user {
 5980: /*  border-left: 5px solid $sidebg; */
 5981:   border-top: 5px solid #000000;
 5982:   margin: 50px 0 0 0;
 5983:   padding: 15px 0 5px 10px;
 5984: }
 5985: 
 5986: div.LC_grade_show_user_odd_row {
 5987: /*  border-left: 5px solid #000000; */
 5988: }
 5989: 
 5990: div.LC_grade_show_user div.LC_Box {
 5991:   margin-right: 50px;
 5992: }
 5993: 
 5994: div.LC_grade_submissions,
 5995: div.LC_grade_message_center,
 5996: div.LC_grade_info_links {
 5997:   margin: 5px;
 5998:   width: 99%;
 5999:   background: #FFFFFF;
 6000: }
 6001: 
 6002: div.LC_grade_submissions_header,
 6003: div.LC_grade_message_center_header {
 6004:   font-weight: bold;
 6005:   font-size: large;
 6006: }
 6007: 
 6008: div.LC_grade_submissions_body,
 6009: div.LC_grade_message_center_body {
 6010:   border: 1px solid black;
 6011:   width: 99%;
 6012:   background: #FFFFFF;
 6013: }
 6014: 
 6015: table.LC_scantron_action {
 6016:   width: 100%;
 6017: }
 6018: 
 6019: table.LC_scantron_action tr th {
 6020:   font-weight:bold;
 6021:   font-style:normal;
 6022: }
 6023: 
 6024: .LC_edit_problem_header,
 6025: div.LC_edit_problem_footer {
 6026:   font-weight: normal;
 6027:   font-size:  medium;
 6028:   margin: 2px;
 6029: }
 6030: 
 6031: div.LC_edit_problem_header,
 6032: div.LC_edit_problem_header div,
 6033: div.LC_edit_problem_footer,
 6034: div.LC_edit_problem_footer div,
 6035: div.LC_edit_problem_editxml_header,
 6036: div.LC_edit_problem_editxml_header div {
 6037:   margin-top: 5px;
 6038: }
 6039: 
 6040: div.LC_edit_problem_header_title {
 6041:   font-weight: bold;
 6042:   font-size: larger;
 6043:   background: $tabbg;
 6044:   padding: 3px;
 6045: }
 6046: 
 6047: table.LC_edit_problem_header_title {
 6048:   width: 100%;
 6049:   background: $tabbg;
 6050: }
 6051: 
 6052: div.LC_edit_problem_discards {
 6053:   float: left;
 6054:   padding-bottom: 5px;
 6055: }
 6056: 
 6057: div.LC_edit_problem_saves {
 6058:   float: right;
 6059:   padding-bottom: 5px;
 6060: }
 6061: 
 6062: img.stift {
 6063:   border-width: 0;
 6064:   vertical-align: middle;
 6065: }
 6066: 
 6067: table td.LC_mainmenu_col_fieldset {
 6068:   vertical-align: top;
 6069: }
 6070: 
 6071: div.LC_createcourse {
 6072:   margin: 10px 10px 10px 10px;
 6073: }
 6074: 
 6075: .LC_dccid {
 6076:   margin: 0.2em 0 0 0;
 6077:   padding: 0;
 6078:   font-size: 90%;
 6079:   display:none;
 6080: }
 6081: 
 6082: a:hover,
 6083: ol.LC_primary_menu a:hover,
 6084: ol#LC_MenuBreadcrumbs a:hover,
 6085: ol#LC_PathBreadcrumbs a:hover,
 6086: ul#LC_secondary_menu a:hover,
 6087: .LC_FormSectionClearButton input:hover
 6088: ul.LC_TabContent   li:hover a {
 6089:   color:$button_hover;
 6090:   text-decoration:none;
 6091: }
 6092: 
 6093: h1 {
 6094:   padding: 0;
 6095:   line-height:130%;
 6096: }
 6097: 
 6098: h2,
 6099: h3,
 6100: h4,
 6101: h5,
 6102: h6 {
 6103:   margin: 5px 0 5px 0;
 6104:   padding: 0;
 6105:   line-height:130%;
 6106: }
 6107: 
 6108: .LC_hcell {
 6109:   padding:3px 15px 3px 15px;
 6110:   margin: 0;
 6111:   background-color:$tabbg;
 6112:   color:$fontmenu;
 6113:   border-bottom:solid 1px $lg_border_color;
 6114: }
 6115: 
 6116: .LC_Box > .LC_hcell {
 6117:   margin: 0 -10px 10px -10px;
 6118: }
 6119: 
 6120: .LC_noBorder {
 6121:   border: 0;
 6122: }
 6123: 
 6124: .LC_FormSectionClearButton input {
 6125:   background-color:transparent;
 6126:   border: none;
 6127:   cursor:pointer;
 6128:   text-decoration:underline;
 6129: }
 6130: 
 6131: .LC_help_open_topic {
 6132:   color: #FFFFFF;
 6133:   background-color: #EEEEFF;
 6134:   margin: 1px;
 6135:   padding: 4px;
 6136:   border: 1px solid #000033;
 6137:   white-space: nowrap;
 6138:   /* vertical-align: middle; */
 6139: }
 6140: 
 6141: dl,
 6142: ul,
 6143: div,
 6144: fieldset {
 6145:   margin: 10px 10px 10px 0;
 6146:   /* overflow: hidden; */
 6147: }
 6148: 
 6149: fieldset > legend {
 6150:   font-weight: bold;
 6151:   padding: 0 5px 0 5px;
 6152: }
 6153: 
 6154: #LC_nav_bar {
 6155:   float: left;
 6156:   background-color: $pgbg_or_bgcolor;
 6157:   margin: 0 0 2px 0;
 6158: }
 6159: 
 6160: #LC_realm {
 6161:   margin: 0.2em 0 0 0;
 6162:   padding: 0;
 6163:   font-weight: bold;
 6164:   text-align: center;
 6165:   background-color: $pgbg_or_bgcolor;
 6166: }
 6167: 
 6168: #LC_nav_bar em {
 6169:   font-weight: bold;
 6170:   font-style: normal;
 6171: }
 6172: 
 6173: /* Preliminary fix to hide nav_bar inside bookmarks window */
 6174: #LC_bookmarks #LC_nav_bar {
 6175:   display:none;
 6176: }
 6177: 
 6178: ol.LC_primary_menu {
 6179:   float: right;
 6180:   margin: 0;
 6181:   background-color: $pgbg_or_bgcolor;
 6182: }
 6183: 
 6184: ol.LC_primary_menu a.LC_new_message {
 6185:   font-weight:bold;
 6186:   color: darkred;
 6187: }
 6188: 
 6189: ol#LC_PathBreadcrumbs {
 6190:   margin: 0;
 6191: }
 6192: 
 6193: ol.LC_primary_menu li {
 6194:   display: inline;
 6195:   padding: 5px 5px 0 10px;
 6196:   vertical-align: top;
 6197: }
 6198: 
 6199: ol.LC_primary_menu li img {
 6200:   vertical-align: bottom;
 6201:   height: 1.1em;
 6202: }
 6203: 
 6204: ol.LC_primary_menu a {
 6205:   color: RGB(80, 80, 80);
 6206:   text-decoration: none;
 6207: }
 6208: 
 6209: ol.LC_docs_parameters {
 6210:   margin-left: 0;
 6211:   padding: 0;
 6212:   list-style: none;
 6213: }
 6214: 
 6215: ol.LC_docs_parameters li {
 6216:   margin: 0;
 6217:   padding-right: 20px;
 6218:   display: inline;
 6219: }
 6220: 
 6221: ol.LC_docs_parameters li:before {
 6222:   content: "\\002022 \\0020";
 6223: }
 6224: 
 6225: li.LC_docs_parameters_title {
 6226:   font-weight: bold;
 6227: }
 6228: 
 6229: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6230:   content: "";
 6231: }
 6232: 
 6233: ul#LC_secondary_menu {
 6234:   clear: both;
 6235:   color: $fontmenu;
 6236:   background: $tabbg;
 6237:   list-style: none;
 6238:   padding: 0;
 6239:   margin: 0;
 6240:   width: 100%;
 6241:   text-align: left;
 6242: }
 6243: 
 6244: ul#LC_secondary_menu li {
 6245:   font-weight: bold;
 6246:   line-height: 1.8em;
 6247:   padding: 0 0.8em;
 6248:   border-right: 1px solid black;
 6249:   display: inline;
 6250:   vertical-align: middle;
 6251: }
 6252: 
 6253: ul.LC_TabContent {
 6254:   display:block;
 6255:   background: $sidebg;
 6256:   border-bottom: solid 1px $lg_border_color;
 6257:   list-style:none;
 6258:   margin: 0 -10px;
 6259:   padding: 0;
 6260: }
 6261: 
 6262: ul.LC_TabContent li,
 6263: ul.LC_TabContentBigger li {
 6264:   float:left;
 6265: }
 6266: 
 6267: ul#LC_secondary_menu li a {
 6268:   color: $fontmenu;
 6269:   text-decoration: none;
 6270: }
 6271: 
 6272: ul.LC_TabContent {
 6273:   min-height:20px;
 6274: }
 6275: 
 6276: ul.LC_TabContent li {
 6277:   vertical-align:middle;
 6278:   padding: 0 16px 0 10px;
 6279:   background-color:$tabbg;
 6280:   border-bottom:solid 1px $lg_border_color;
 6281:   border-right: solid 1px $font;
 6282: }
 6283: 
 6284: ul.LC_TabContent .right {
 6285:   float:right;
 6286: }
 6287: 
 6288: ul.LC_TabContent li a,
 6289: ul.LC_TabContent li {
 6290:   color:rgb(47,47,47);
 6291:   text-decoration:none;
 6292:   font-size:95%;
 6293:   font-weight:bold;
 6294:   min-height:20px;
 6295: }
 6296: 
 6297: ul.LC_TabContent li a:hover,
 6298: ul.LC_TabContent li a:focus {
 6299:   color: $button_hover;
 6300:   background:none;
 6301:   outline:none;
 6302: }
 6303: 
 6304: ul.LC_TabContent li:hover {
 6305:   color: $button_hover;
 6306:   cursor:pointer;
 6307: }
 6308: 
 6309: ul.LC_TabContent li.active {
 6310:   color: $font;
 6311:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6312:   border-bottom:solid 1px #FFFFFF;
 6313:   cursor: default;
 6314: }
 6315: 
 6316: ul.LC_TabContent li.active a {
 6317:   color:$font;
 6318:   background:#FFFFFF;
 6319:   outline: none;
 6320: }
 6321: #maincoursedoc {
 6322:   clear:both;
 6323: }
 6324: 
 6325: ul.LC_TabContentBigger {
 6326:   display:block;
 6327:   list-style:none;
 6328:   padding: 0;
 6329: }
 6330: 
 6331: ul.LC_TabContentBigger li {
 6332:   vertical-align:bottom;
 6333:   height: 30px;
 6334:   font-size:110%;
 6335:   font-weight:bold;
 6336:   color: #737373;
 6337: }
 6338: 
 6339: ul.LC_TabContentBigger li.active {
 6340:   position: relative;
 6341:   top: 1px;
 6342: }
 6343: 
 6344: ul.LC_TabContentBigger li a {
 6345:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6346:   height: 30px;
 6347:   line-height: 30px;
 6348:   text-align: center;
 6349:   display: block;
 6350:   text-decoration: none;
 6351:   outline: none;
 6352: }
 6353: 
 6354: ul.LC_TabContentBigger li.active a {
 6355:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6356:   color:$font;
 6357: }
 6358: 
 6359: ul.LC_TabContentBigger li b {
 6360:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6361:   display: block;
 6362:   float: left;
 6363:   padding: 0 30px;
 6364:   border-bottom: 1px solid $lg_border_color;
 6365: }
 6366: 
 6367: ul.LC_TabContentBigger li:hover b {
 6368:   color:$button_hover;
 6369: }
 6370: 
 6371: ul.LC_TabContentBigger li.active b {
 6372:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6373:   color:$font;
 6374:   border: 0;
 6375:   cursor:default;
 6376: }
 6377: 
 6378: ul.LC_CourseBreadcrumbs {
 6379:   background: $sidebg;
 6380:   line-height: 32px;
 6381:   padding-left: 10px;
 6382:   margin: 0 0 10px 0;
 6383:   list-style-position: inside;
 6384: 
 6385: }
 6386: 
 6387: ol#LC_MenuBreadcrumbs,
 6388: ol#LC_PathBreadcrumbs {
 6389:   padding-left: 10px;
 6390:   margin: 0;
 6391:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6392: }
 6393: 
 6394: ol#LC_MenuBreadcrumbs li,
 6395: ol#LC_PathBreadcrumbs li,
 6396: ul.LC_CourseBreadcrumbs li {
 6397:   display: inline;
 6398:   white-space: normal;  
 6399: }
 6400: 
 6401: ol#LC_MenuBreadcrumbs li a,
 6402: ul.LC_CourseBreadcrumbs li a {
 6403:   text-decoration: none;
 6404:   font-size:90%;
 6405: }
 6406: 
 6407: ol#LC_MenuBreadcrumbs h1 {
 6408:   display: inline;
 6409:   font-size: 90%;
 6410:   line-height: 2.5em;
 6411:   margin: 0;
 6412:   padding: 0;
 6413: }
 6414: 
 6415: ol#LC_PathBreadcrumbs li a {
 6416:   text-decoration:none;
 6417:   font-size:100%;
 6418:   font-weight:bold;
 6419: }
 6420: 
 6421: .LC_Box {
 6422:   border: solid 1px $lg_border_color;
 6423:   padding: 0 10px 10px 10px;
 6424: }
 6425: 
 6426: .LC_AboutMe_Image {
 6427:   float:left;
 6428:   margin-right:10px;
 6429: }
 6430: 
 6431: .LC_Clear_AboutMe_Image {
 6432:   clear:left;
 6433: }
 6434: 
 6435: dl.LC_ListStyleClean dt {
 6436:   padding-right: 5px;
 6437:   display: table-header-group;
 6438: }
 6439: 
 6440: dl.LC_ListStyleClean dd {
 6441:   display: table-row;
 6442: }
 6443: 
 6444: .LC_ListStyleClean,
 6445: .LC_ListStyleSimple,
 6446: .LC_ListStyleNormal,
 6447: .LC_ListStyleSpecial {
 6448:   /* display:block; */
 6449:   list-style-position: inside;
 6450:   list-style-type: none;
 6451:   overflow: hidden;
 6452:   padding: 0;
 6453: }
 6454: 
 6455: .LC_ListStyleSimple li,
 6456: .LC_ListStyleSimple dd,
 6457: .LC_ListStyleNormal li,
 6458: .LC_ListStyleNormal dd,
 6459: .LC_ListStyleSpecial li,
 6460: .LC_ListStyleSpecial dd {
 6461:   margin: 0;
 6462:   padding: 5px 5px 5px 10px;
 6463:   clear: both;
 6464: }
 6465: 
 6466: .LC_ListStyleClean li,
 6467: .LC_ListStyleClean dd {
 6468:   padding-top: 0;
 6469:   padding-bottom: 0;
 6470: }
 6471: 
 6472: .LC_ListStyleSimple dd,
 6473: .LC_ListStyleSimple li {
 6474:   border-bottom: solid 1px $lg_border_color;
 6475: }
 6476: 
 6477: .LC_ListStyleSpecial li,
 6478: .LC_ListStyleSpecial dd {
 6479:   list-style-type: none;
 6480:   background-color: RGB(220, 220, 220);
 6481:   margin-bottom: 4px;
 6482: }
 6483: 
 6484: table.LC_SimpleTable {
 6485:   margin:5px;
 6486:   border:solid 1px $lg_border_color;
 6487: }
 6488: 
 6489: table.LC_SimpleTable tr {
 6490:   padding: 0;
 6491:   border:solid 1px $lg_border_color;
 6492: }
 6493: 
 6494: table.LC_SimpleTable thead {
 6495:   background:rgb(220,220,220);
 6496: }
 6497: 
 6498: div.LC_columnSection {
 6499:   display: block;
 6500:   clear: both;
 6501:   overflow: hidden;
 6502:   margin: 0;
 6503: }
 6504: 
 6505: div.LC_columnSection>* {
 6506:   float: left;
 6507:   margin: 10px 20px 10px 0;
 6508:   overflow:hidden;
 6509: }
 6510: 
 6511: table em {
 6512:   font-weight: bold;
 6513:   font-style: normal;
 6514: }
 6515: 
 6516: table.LC_tableBrowseRes,
 6517: table.LC_tableOfContent {
 6518:   border:none;
 6519:   border-spacing: 1px;
 6520:   padding: 3px;
 6521:   background-color: #FFFFFF;
 6522:   font-size: 90%;
 6523: }
 6524: 
 6525: table.LC_tableOfContent {
 6526:   border-collapse: collapse;
 6527: }
 6528: 
 6529: table.LC_tableBrowseRes a,
 6530: table.LC_tableOfContent a {
 6531:   background-color: transparent;
 6532:   text-decoration: none;
 6533: }
 6534: 
 6535: table.LC_tableOfContent img {
 6536:   border: none;
 6537:   height: 1.3em;
 6538:   vertical-align: text-bottom;
 6539:   margin-right: 0.3em;
 6540: }
 6541: 
 6542: a#LC_content_toolbar_firsthomework {
 6543:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6544: }
 6545: 
 6546: a#LC_content_toolbar_launchnav {
 6547:   background-image:url(/res/adm/pages/start-navigation.gif);
 6548: }
 6549: 
 6550: a#LC_content_toolbar_closenav {
 6551:   background-image:url(/res/adm/pages/close-navigation.gif);
 6552: }
 6553: 
 6554: a#LC_content_toolbar_everything {
 6555:   background-image:url(/res/adm/pages/show-all.gif);
 6556: }
 6557: 
 6558: a#LC_content_toolbar_uncompleted {
 6559:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6560: }
 6561: 
 6562: #LC_content_toolbar_clearbubbles {
 6563:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6564: }
 6565: 
 6566: a#LC_content_toolbar_changefolder {
 6567:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6568: }
 6569: 
 6570: a#LC_content_toolbar_changefolder_toggled {
 6571:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6572: }
 6573: 
 6574: ul#LC_toolbar li a:hover {
 6575:   background-position: bottom center;
 6576: }
 6577: 
 6578: ul#LC_toolbar {
 6579:   padding: 0;
 6580:   margin: 2px;
 6581:   list-style:none;
 6582:   position:relative;
 6583:   background-color:white;
 6584: }
 6585: 
 6586: ul#LC_toolbar li {
 6587:   border:1px solid white;
 6588:   padding: 0;
 6589:   margin: 0;
 6590:   float: left;
 6591:   display:inline;
 6592:   vertical-align:middle;
 6593: }
 6594: 
 6595: 
 6596: a.LC_toolbarItem {
 6597:   display:block;
 6598:   padding: 0;
 6599:   margin: 0;
 6600:   height: 32px;
 6601:   width: 32px;
 6602:   color:white;
 6603:   border: none;
 6604:   background-repeat:no-repeat;
 6605:   background-color:transparent;
 6606: }
 6607: 
 6608: ul.LC_funclist {
 6609:     margin: 0;
 6610:     padding: 0.5em 1em 0.5em 0;
 6611: }
 6612: 
 6613: ul.LC_funclist > li:first-child {
 6614:     font-weight:bold; 
 6615:     margin-left:0.8em;
 6616: }
 6617: 
 6618: ul.LC_funclist + ul.LC_funclist {
 6619:     /* 
 6620:        left border as a seperator if we have more than
 6621:        one list 
 6622:     */
 6623:     border-left: 1px solid $sidebg;
 6624:     /* 
 6625:        this hides the left border behind the border of the 
 6626:        outer box if element is wrapped to the next 'line' 
 6627:     */
 6628:     margin-left: -1px;
 6629: }
 6630: 
 6631: ul.LC_funclist li {
 6632:   display: inline;
 6633:   white-space: nowrap;
 6634:   margin: 0 0 0 25px;
 6635:   line-height: 150%;
 6636: }
 6637: 
 6638: .ui-accordion .LC_advanced_toggle {
 6639:   float: right;
 6640:   font-size: 90%;
 6641:   padding: 0px 4px
 6642: }
 6643: 
 6644: END
 6645: }
 6646: 
 6647: =pod
 6648: 
 6649: =item * &headtag()
 6650: 
 6651: Returns a uniform footer for LON-CAPA web pages.
 6652: 
 6653: Inputs: $title - optional title for the head
 6654:         $head_extra - optional extra HTML to put inside the <head>
 6655:         $args - optional arguments
 6656:             force_register - if is true call registerurl so the remote is 
 6657:                              informed
 6658:             redirect       -> array ref of
 6659:                                    1- seconds before redirect occurs
 6660:                                    2- url to redirect to
 6661:                                    3- whether the side effect should occur
 6662:                            (side effect of setting 
 6663:                                $env{'internal.head.redirect'} to the url 
 6664:                                redirected too)
 6665:             domain         -> force to color decorate a page for a specific
 6666:                                domain
 6667:             function       -> force usage of a specific rolish color scheme
 6668:             bgcolor        -> override the default page bgcolor
 6669:             no_auto_mt_title
 6670:                            -> prevent &mt()ing the title arg
 6671: 
 6672: =cut
 6673: 
 6674: sub headtag {
 6675:     my ($title,$head_extra,$args) = @_;
 6676:     
 6677:     my $function = $args->{'function'} || &get_users_function();
 6678:     my $domain   = $args->{'domain'}   || &determinedomain();
 6679:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6680:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6681: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6682: 		   #time(),
 6683: 		   $env{'environment.color.timestamp'},
 6684: 		   $function,$domain,$bgcolor);
 6685: 
 6686:     $url = '/adm/css/'.&escape($url).'.css';
 6687: 
 6688:     my $result =
 6689: 	'<head>'.
 6690: 	&font_settings();
 6691: 
 6692:     if (!$args->{'frameset'}) {
 6693: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6694:     }
 6695:     if ($args->{'force_register'}) {
 6696: 	$result .= &Apache::lonmenu::registerurl(1);
 6697:     }
 6698:     if (!$args->{'no_nav_bar'} 
 6699: 	&& !$args->{'only_body'}
 6700: 	&& !$args->{'frameset'}) {
 6701: 	$result .= &help_menu_js();
 6702:     }
 6703: 
 6704:     if (ref($args->{'redirect'})) {
 6705: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6706: 	$url = &Apache::lonenc::check_encrypt($url);
 6707: 	if (!$inhibit_continue) {
 6708: 	    $env{'internal.head.redirect'} = $url;
 6709: 	}
 6710: 	$result.=<<ADDMETA
 6711: <meta http-equiv="pragma" content="no-cache" />
 6712: <meta http-equiv="Refresh" content="$time; url=$url" />
 6713: ADDMETA
 6714:     }
 6715:     if (!defined($title)) {
 6716: 	$title = 'The LearningOnline Network with CAPA';
 6717:     }
 6718:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6719:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6720: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6721: 	.$head_extra;
 6722:     return $result;
 6723: }
 6724: 
 6725: =pod
 6726: 
 6727: =item * &font_settings()
 6728: 
 6729: Returns neccessary <meta> to set the proper encoding
 6730: 
 6731: Inputs: none
 6732: 
 6733: =cut
 6734: 
 6735: sub font_settings {
 6736:     my $headerstring='';
 6737:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6738: 	$headerstring.=
 6739: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6740:     }
 6741:     return $headerstring;
 6742: }
 6743: 
 6744: =pod
 6745: 
 6746: =item * &xml_begin()
 6747: 
 6748: Returns the needed doctype and <html>
 6749: 
 6750: Inputs: none
 6751: 
 6752: =cut
 6753: 
 6754: sub xml_begin {
 6755:     my $output='';
 6756: 
 6757:     if ($env{'browser.mathml'}) {
 6758: 	$output='<?xml version="1.0"?>'
 6759:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6760: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6761:             
 6762: #	    .'<!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">] >'
 6763: 	    .'<!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">'
 6764:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6765: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6766:     } else {
 6767: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6768:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6769:     }
 6770:     return $output;
 6771: }
 6772: 
 6773: =pod
 6774: 
 6775: =item * &endheadtag()
 6776: 
 6777: Returns a uniform </head> for LON-CAPA web pages.
 6778: 
 6779: Inputs: none
 6780: 
 6781: =cut
 6782: 
 6783: sub endheadtag {
 6784:     return '</head>';
 6785: }
 6786: 
 6787: =pod
 6788: 
 6789: =item * &head()
 6790: 
 6791: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6792: 
 6793: Inputs:
 6794: 
 6795: =over 4
 6796: 
 6797: $title - optional title for the page
 6798: 
 6799: $head_extra - optional extra HTML to put inside the <head>
 6800: 
 6801: =back
 6802: 
 6803: =cut
 6804: 
 6805: sub head {
 6806:     my ($title,$head_extra,$args) = @_;
 6807:     return &headtag($title,$head_extra,$args).&endheadtag();
 6808: }
 6809: 
 6810: =pod
 6811: 
 6812: =item * &start_page()
 6813: 
 6814: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6815: 
 6816: Inputs:
 6817: 
 6818: =over 4
 6819: 
 6820: $title - optional title for the page
 6821: 
 6822: $head_extra - optional extra HTML to incude inside the <head>
 6823: 
 6824: $args - additional optional args supported are:
 6825: 
 6826: =over 8
 6827: 
 6828:              only_body      -> is true will set &bodytag() onlybodytag
 6829:                                     arg on
 6830:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6831:              add_entries    -> additional attributes to add to the  <body>
 6832:              domain         -> force to color decorate a page for a 
 6833:                                     specific domain
 6834:              function       -> force usage of a specific rolish color
 6835:                                     scheme
 6836:              redirect       -> see &headtag()
 6837:              bgcolor        -> override the default page bg color
 6838:              js_ready       -> return a string ready for being used in 
 6839:                                     a javascript writeln
 6840:              html_encode    -> return a string ready for being used in 
 6841:                                     a html attribute
 6842:              force_register -> if is true will turn on the &bodytag()
 6843:                                     $forcereg arg
 6844:              frameset       -> if true will start with a <frameset>
 6845:                                     rather than <body>
 6846:              skip_phases    -> hash ref of 
 6847:                                     head -> skip the <html><head> generation
 6848:                                     body -> skip all <body> generation
 6849:              no_inline_link -> if true and in remote mode, don't show the 
 6850:                                     'Switch To Inline Menu' link
 6851:              no_auto_mt_title -> prevent &mt()ing the title arg
 6852:              inherit_jsmath -> when creating popup window in a page,
 6853:                                     should it have jsmath forced on by the
 6854:                                     current page
 6855:              bread_crumbs ->             Array containing breadcrumbs
 6856:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 6857: 
 6858: =back
 6859: 
 6860: =back
 6861: 
 6862: =cut
 6863: 
 6864: sub start_page {
 6865:     my ($title,$head_extra,$args) = @_;
 6866:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6867:     my %head_args;
 6868:     foreach my $arg ('redirect','force_register','domain','function',
 6869: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6870: 		     'no_auto_mt_title') {
 6871: 	if (defined($args->{$arg})) {
 6872: 	    $head_args{$arg} = $args->{$arg};
 6873: 	}
 6874:     }
 6875: 
 6876:     $env{'internal.start_page'}++;
 6877:     my $result;
 6878:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6879: 	$result.=
 6880: 	    &xml_begin().
 6881: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6882:     }
 6883:     
 6884:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6885: 	if ($args->{'frameset'}) {
 6886: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6887: 						$args->{'add_entries'});
 6888: 	    $result .= "\n<frameset $attr_string>\n";
 6889:         } else {
 6890:             $result .=
 6891:                 &bodytag($title, 
 6892:                          $args->{'function'},       $args->{'add_entries'},
 6893:                          $args->{'only_body'},      $args->{'domain'},
 6894:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6895:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 6896:                          $args);
 6897:         }
 6898:     }
 6899: 
 6900:     if ($args->{'js_ready'}) {
 6901: 		$result = &js_ready($result);
 6902:     }
 6903:     if ($args->{'html_encode'}) {
 6904: 		$result = &html_encode($result);
 6905:     }
 6906: 
 6907:     # Preparation for new and consistent functionlist at top of screen
 6908:     # if ($args->{'functionlist'}) {
 6909:     #            $result .= &build_functionlist();
 6910:     #}
 6911: 
 6912:     # Don't add anything more if only_body wanted
 6913:     return $result if $args->{'only_body'};
 6914: 
 6915:     #Breadcrumbs for Construction Space provided by &bodytag. 
 6916:     if (($env{'environment.remote'} eq 'off') && ($env{'request.state'} eq 'construct')) {
 6917:         return $result;
 6918:     }
 6919:  
 6920:     #Breadcrumbs
 6921:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6922: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6923: 		#if any br links exists, add them to the breadcrumbs
 6924: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6925: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6926: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6927: 			}
 6928: 		}
 6929: 
 6930: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6931: 		if(exists($args->{'bread_crumbs_component'})){
 6932: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6933: 		}else{
 6934: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6935: 		}
 6936:     }
 6937:     return $result;
 6938: }
 6939: 
 6940: 
 6941: =pod
 6942: 
 6943: =item * &head()
 6944: 
 6945: Returns a complete </body></html> section for LON-CAPA web pages.
 6946: 
 6947: Inputs:         $args - additional optional args supported are:
 6948:                  js_ready     -> return a string ready for being used in 
 6949:                                  a javascript writeln
 6950:                  html_encode  -> return a string ready for being used in 
 6951:                                  a html attribute
 6952:                  frameset     -> if true will start with a <frameset>
 6953:                                  rather than <body>
 6954:                  dicsussion   -> if true will get discussion from
 6955:                                   lonxml::xmlend
 6956:                                  (you can pass the target and parser arguments
 6957:                                   through optional 'target' and 'parser' args
 6958:                                   to this routine)
 6959: 
 6960: =cut
 6961: 
 6962: sub end_page {
 6963:     my ($args) = @_;
 6964:     $env{'internal.end_page'}++;
 6965:     my $result;
 6966:     if ($args->{'discussion'}) {
 6967: 	my ($target,$parser);
 6968: 	if (ref($args->{'discussion'})) {
 6969: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6970: 				$args->{'discussion'}{'parser'});
 6971: 	}
 6972: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6973:     }
 6974: 
 6975:     if ($args->{'frameset'}) {
 6976: 	$result .= '</frameset>';
 6977:     } else {
 6978: 	$result .= &endbodytag($args);
 6979:     }
 6980:     $result .= "\n</html>";
 6981: 
 6982:     if ($args->{'js_ready'}) {
 6983: 	$result = &js_ready($result);
 6984:     }
 6985: 
 6986:     if ($args->{'html_encode'}) {
 6987: 	$result = &html_encode($result);
 6988:     }
 6989: 
 6990:     return $result;
 6991: }
 6992: 
 6993: sub html_encode {
 6994:     my ($result) = @_;
 6995: 
 6996:     $result = &HTML::Entities::encode($result,'<>&"');
 6997:     
 6998:     return $result;
 6999: }
 7000: sub js_ready {
 7001:     my ($result) = @_;
 7002: 
 7003:     $result =~ s/[\n\r]/ /xmsg;
 7004:     $result =~ s/\\/\\\\/xmsg;
 7005:     $result =~ s/'/\\'/xmsg;
 7006:     $result =~ s{</}{<\\/}xmsg;
 7007:     
 7008:     return $result;
 7009: }
 7010: 
 7011: sub validate_page {
 7012:     if (  exists($env{'internal.start_page'})
 7013: 	  &&     $env{'internal.start_page'} > 1) {
 7014: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7015: 				 $env{'internal.start_page'}.' '.
 7016: 				 $ENV{'request.filename'});
 7017:     }
 7018:     if (  exists($env{'internal.end_page'})
 7019: 	  &&     $env{'internal.end_page'} > 1) {
 7020: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7021: 				 $env{'internal.end_page'}.' '.
 7022: 				 $env{'request.filename'});
 7023:     }
 7024:     if (     exists($env{'internal.start_page'})
 7025: 	&& ! exists($env{'internal.end_page'})) {
 7026: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7027: 				 $env{'request.filename'});
 7028:     }
 7029:     if (   ! exists($env{'internal.start_page'})
 7030: 	&&   exists($env{'internal.end_page'})) {
 7031: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7032: 				 $env{'request.filename'});
 7033:     }
 7034: }
 7035: 
 7036: sub simple_error_page {
 7037:     my ($r,$title,$msg) = @_;
 7038:     my $page =
 7039: 	&Apache::loncommon::start_page($title).
 7040: 	&mt($msg).
 7041: 	&Apache::loncommon::end_page();
 7042:     if (ref($r)) {
 7043: 	$r->print($page);
 7044: 	return;
 7045:     }
 7046:     return $page;
 7047: }
 7048: 
 7049: {
 7050:     my @row_count;
 7051: 
 7052:     sub start_data_table_count {
 7053:         unshift(@row_count, 0);
 7054:         return;
 7055:     }
 7056: 
 7057:     sub end_data_table_count {
 7058:         shift(@row_count);
 7059:         return;
 7060:     }
 7061: 
 7062:     sub start_data_table {
 7063: 	my ($add_class) = @_;
 7064: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7065:         &start_data_table_count();
 7066: 	return '<table class="'.$css_class.'">'."\n";
 7067:     }
 7068: 
 7069:     sub end_data_table {
 7070:         &end_data_table_count();
 7071: 	return '</table>'."\n";;
 7072:     }
 7073: 
 7074:     sub start_data_table_row {
 7075: 	my ($add_class) = @_;
 7076: 	$row_count[0]++;
 7077: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7078: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7079: 	return  '<tr class="'.$css_class.'">'."\n";;
 7080:     }
 7081:     
 7082:     sub continue_data_table_row {
 7083: 	my ($add_class) = @_;
 7084: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7085: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');;
 7086: 	return  '<tr class="'.$css_class.'">'."\n";;
 7087:     }
 7088: 
 7089:     sub end_data_table_row {
 7090: 	return '</tr>'."\n";;
 7091:     }
 7092: 
 7093:     sub start_data_table_empty_row {
 7094: #	$row_count[0]++;
 7095: 	return  '<tr class="LC_empty_row" >'."\n";;
 7096:     }
 7097: 
 7098:     sub end_data_table_empty_row {
 7099: 	return '</tr>'."\n";;
 7100:     }
 7101: 
 7102:     sub start_data_table_header_row {
 7103: 	return  '<tr class="LC_header_row">'."\n";;
 7104:     }
 7105: 
 7106:     sub end_data_table_header_row {
 7107: 	return '</tr>'."\n";;
 7108:     }
 7109: 
 7110:     sub data_table_caption {
 7111:         my $caption = shift;
 7112:         return "<caption class=\"LC_caption\">$caption</caption>";
 7113:     }
 7114: }
 7115: 
 7116: =pod
 7117: 
 7118: =item * &inhibit_menu_check($arg)
 7119: 
 7120: Checks for a inhibitmenu state and generates output to preserve it
 7121: 
 7122: Inputs:         $arg - can be any of
 7123:                      - undef - in which case the return value is a string 
 7124:                                to add  into arguments list of a uri
 7125:                      - 'input' - in which case the return value is a HTML
 7126:                                  <form> <input> field of type hidden to
 7127:                                  preserve the value
 7128:                      - a url - in which case the return value is the url with
 7129:                                the neccesary cgi args added to preserve the
 7130:                                inhibitmenu state
 7131:                      - a ref to a url - no return value, but the string is
 7132:                                         updated to include the neccessary cgi
 7133:                                         args to preserve the inhibitmenu state
 7134: 
 7135: =cut
 7136: 
 7137: sub inhibit_menu_check {
 7138:     my ($arg) = @_;
 7139:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7140:     if ($arg eq 'input') {
 7141: 	if ($env{'form.inhibitmenu'}) {
 7142: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7143: 	} else {
 7144: 	    return
 7145: 	}
 7146:     }
 7147:     if ($env{'form.inhibitmenu'}) {
 7148: 	if (ref($arg)) {
 7149: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7150: 	} elsif ($arg eq '') {
 7151: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7152: 	} else {
 7153: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7154: 	}
 7155:     }
 7156:     if (!ref($arg)) {
 7157: 	return $arg;
 7158:     }
 7159: }
 7160: 
 7161: ###############################################
 7162: 
 7163: =pod
 7164: 
 7165: =back
 7166: 
 7167: =head1 User Information Routines
 7168: 
 7169: =over 4
 7170: 
 7171: =item * &get_users_function()
 7172: 
 7173: Used by &bodytag to determine the current users primary role.
 7174: Returns either 'student','coordinator','admin', or 'author'.
 7175: 
 7176: =cut
 7177: 
 7178: ###############################################
 7179: sub get_users_function {
 7180:     my $function = 'norole';
 7181:     if ($env{'request.role'}=~/^(st)/) {
 7182:         $function='student';
 7183:     }
 7184:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7185:         $function='coordinator';
 7186:     }
 7187:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7188:         $function='admin';
 7189:     }
 7190:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7191:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 7192:         $function='author';
 7193:     }
 7194:     return $function;
 7195: }
 7196: 
 7197: ###############################################
 7198: 
 7199: =pod
 7200: 
 7201: =item * &show_course()
 7202: 
 7203: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7204: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7205: 
 7206: Inputs:
 7207: None
 7208: 
 7209: Outputs:
 7210: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7211: 
 7212: =cut
 7213: 
 7214: ###############################################
 7215: sub show_course {
 7216:     my $course = !$env{'user.adv'};
 7217:     if (!$env{'user.adv'}) {
 7218:         foreach my $env (keys(%env)) {
 7219:             next if ($env !~ m/^user\.priv\./);
 7220:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7221:                 $course = 0;
 7222:                 last;
 7223:             }
 7224:         }
 7225:     }
 7226:     return $course;
 7227: }
 7228: 
 7229: ###############################################
 7230: 
 7231: =pod
 7232: 
 7233: =item * &check_user_status()
 7234: 
 7235: Determines current status of supplied role for a
 7236: specific user. Roles can be active, previous or future.
 7237: 
 7238: Inputs: 
 7239: user's domain, user's username, course's domain,
 7240: course's number, optional section ID.
 7241: 
 7242: Outputs:
 7243: role status: active, previous or future. 
 7244: 
 7245: =cut
 7246: 
 7247: sub check_user_status {
 7248:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7249:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 7250:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
 7251:     my @uroles = keys %userinfo;
 7252:     my $srchstr;
 7253:     my $active_chk = 'none';
 7254:     my $now = time;
 7255:     if (@uroles > 0) {
 7256:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7257:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7258:         } else {
 7259:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7260:         }
 7261:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7262:             my $role_end = 0;
 7263:             my $role_start = 0;
 7264:             $active_chk = 'active';
 7265:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7266:                 $role_end = $1;
 7267:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7268:                     $role_start = $1;
 7269:                 }
 7270:             }
 7271:             if ($role_start > 0) {
 7272:                 if ($now < $role_start) {
 7273:                     $active_chk = 'future';
 7274:                 }
 7275:             }
 7276:             if ($role_end > 0) {
 7277:                 if ($now > $role_end) {
 7278:                     $active_chk = 'previous';
 7279:                 }
 7280:             }
 7281:         }
 7282:     }
 7283:     return $active_chk;
 7284: }
 7285: 
 7286: ###############################################
 7287: 
 7288: =pod
 7289: 
 7290: =item * &get_sections()
 7291: 
 7292: Determines all the sections for a course including
 7293: sections with students and sections containing other roles.
 7294: Incoming parameters: 
 7295: 
 7296: 1. domain
 7297: 2. course number 
 7298: 3. reference to array containing roles for which sections should 
 7299: be gathered (optional).
 7300: 4. reference to array containing status types for which sections 
 7301: should be gathered (optional).
 7302: 
 7303: If the third argument is undefined, sections are gathered for any role. 
 7304: If the fourth argument is undefined, sections are gathered for any status.
 7305: Permissible values are 'active' or 'future' or 'previous'.
 7306:  
 7307: Returns section hash (keys are section IDs, values are
 7308: number of users in each section), subject to the
 7309: optional roles filter, optional status filter 
 7310: 
 7311: =cut
 7312: 
 7313: ###############################################
 7314: sub get_sections {
 7315:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7316:     if (!defined($cdom) || !defined($cnum)) {
 7317:         my $cid =  $env{'request.course.id'};
 7318: 
 7319: 	return if (!defined($cid));
 7320: 
 7321:         $cdom = $env{'course.'.$cid.'.domain'};
 7322:         $cnum = $env{'course.'.$cid.'.num'};
 7323:     }
 7324: 
 7325:     my %sectioncount;
 7326:     my $now = time;
 7327: 
 7328:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7329: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7330: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7331: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7332:         my $start_index = &Apache::loncoursedata::CL_START();
 7333:         my $end_index = &Apache::loncoursedata::CL_END();
 7334:         my $status;
 7335: 	while (my ($student,$data) = each(%$classlist)) {
 7336: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7337: 				                     $data->[$status_index],
 7338:                                                      $data->[$start_index],
 7339:                                                      $data->[$end_index]);
 7340:             if ($stu_status eq 'Active') {
 7341:                 $status = 'active';
 7342:             } elsif ($end < $now) {
 7343:                 $status = 'previous';
 7344:             } elsif ($start > $now) {
 7345:                 $status = 'future';
 7346:             } 
 7347: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7348:                 if ((!defined($possible_status)) || (($status ne '') && 
 7349:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7350: 		    $sectioncount{$section}++;
 7351:                 }
 7352: 	    }
 7353: 	}
 7354:     }
 7355:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7356:     foreach my $user (sort(keys(%courseroles))) {
 7357: 	if ($user !~ /^(\w{2})/) { next; }
 7358: 	my ($role) = ($user =~ /^(\w{2})/);
 7359: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7360: 	my ($section,$status);
 7361: 	if ($role eq 'cr' &&
 7362: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7363: 	    $section=$1;
 7364: 	}
 7365: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7366: 	if (!defined($section) || $section eq '-1') { next; }
 7367:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7368:         if ($end == -1 && $start == -1) {
 7369:             next; #deleted role
 7370:         }
 7371:         if (!defined($possible_status)) { 
 7372:             $sectioncount{$section}++;
 7373:         } else {
 7374:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7375:                 $status = 'active';
 7376:             } elsif ($end < $now) {
 7377:                 $status = 'future';
 7378:             } elsif ($start > $now) {
 7379:                 $status = 'previous';
 7380:             }
 7381:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7382:                 $sectioncount{$section}++;
 7383:             }
 7384:         }
 7385:     }
 7386:     return %sectioncount;
 7387: }
 7388: 
 7389: ###############################################
 7390: 
 7391: =pod
 7392: 
 7393: =item * &get_course_users()
 7394: 
 7395: Retrieves usernames:domains for users in the specified course
 7396: with specific role(s), and access status. 
 7397: 
 7398: Incoming parameters:
 7399: 1. course domain
 7400: 2. course number
 7401: 3. access status: users must have - either active, 
 7402: previous, future, or all.
 7403: 4. reference to array of permissible roles
 7404: 5. reference to array of section restrictions (optional)
 7405: 6. reference to results object (hash of hashes).
 7406: 7. reference to optional userdata hash
 7407: 8. reference to optional statushash
 7408: 9. flag if privileged users (except those set to unhide in
 7409:    course settings) should be excluded    
 7410: Keys of top level results hash are roles.
 7411: Keys of inner hashes are username:domain, with 
 7412: values set to access type.
 7413: Optional userdata hash returns an array with arguments in the 
 7414: same order as loncoursedata::get_classlist() for student data.
 7415: 
 7416: Optional statushash returns
 7417: 
 7418: Entries for end, start, section and status are blank because
 7419: of the possibility of multiple values for non-student roles.
 7420: 
 7421: =cut
 7422: 
 7423: ###############################################
 7424: 
 7425: sub get_course_users {
 7426:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7427:     my %idx = ();
 7428:     my %seclists;
 7429: 
 7430:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7431:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7432:     $idx{end} = &Apache::loncoursedata::CL_END();
 7433:     $idx{start} = &Apache::loncoursedata::CL_START();
 7434:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7435:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7436:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7437:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7438: 
 7439:     if (grep(/^st$/,@{$roles})) {
 7440:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7441:         my $now = time;
 7442:         foreach my $student (keys(%{$classlist})) {
 7443:             my $match = 0;
 7444:             my $secmatch = 0;
 7445:             my $section = $$classlist{$student}[$idx{section}];
 7446:             my $status = $$classlist{$student}[$idx{status}];
 7447:             if ($section eq '') {
 7448:                 $section = 'none';
 7449:             }
 7450:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7451:                 if (grep(/^all$/,@{$sections})) {
 7452:                     $secmatch = 1;
 7453:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7454:                     if (grep(/^none$/,@{$sections})) {
 7455:                         $secmatch = 1;
 7456:                     }
 7457:                 } else {  
 7458: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7459: 		        $secmatch = 1;
 7460:                     }
 7461: 		}
 7462:                 if (!$secmatch) {
 7463:                     next;
 7464:                 }
 7465:             }
 7466:             if (defined($$types{'active'})) {
 7467:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7468:                     push(@{$$users{st}{$student}},'active');
 7469:                     $match = 1;
 7470:                 }
 7471:             }
 7472:             if (defined($$types{'previous'})) {
 7473:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7474:                     push(@{$$users{st}{$student}},'previous');
 7475:                     $match = 1;
 7476:                 }
 7477:             }
 7478:             if (defined($$types{'future'})) {
 7479:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7480:                     push(@{$$users{st}{$student}},'future');
 7481:                     $match = 1;
 7482:                 }
 7483:             }
 7484:             if ($match) {
 7485:                 push(@{$seclists{$student}},$section);
 7486:                 if (ref($userdata) eq 'HASH') {
 7487:                     $$userdata{$student} = $$classlist{$student};
 7488:                 }
 7489:                 if (ref($statushash) eq 'HASH') {
 7490:                     $statushash->{$student}{'st'}{$section} = $status;
 7491:                 }
 7492:             }
 7493:         }
 7494:     }
 7495:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7496:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7497:         my $now = time;
 7498:         my %displaystatus = ( previous => 'Expired',
 7499:                               active   => 'Active',
 7500:                               future   => 'Future',
 7501:                             );
 7502:         my %nothide;
 7503:         if ($hidepriv) {
 7504:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7505:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7506:                 if ($user !~ /:/) {
 7507:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7508:                 } else {
 7509:                     $nothide{$user} = 1;
 7510:                 }
 7511:             }
 7512:         }
 7513:         foreach my $person (sort(keys(%coursepersonnel))) {
 7514:             my $match = 0;
 7515:             my $secmatch = 0;
 7516:             my $status;
 7517:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7518:             $user =~ s/:$//;
 7519:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7520:             if ($end == -1 || $start == -1) {
 7521:                 next;
 7522:             }
 7523:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7524:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7525:                 my ($uname,$udom) = split(/:/,$user);
 7526:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7527:                     if (grep(/^all$/,@{$sections})) {
 7528:                         $secmatch = 1;
 7529:                     } elsif ($usec eq '') {
 7530:                         if (grep(/^none$/,@{$sections})) {
 7531:                             $secmatch = 1;
 7532:                         }
 7533:                     } else {
 7534:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7535:                             $secmatch = 1;
 7536:                         }
 7537:                     }
 7538:                     if (!$secmatch) {
 7539:                         next;
 7540:                     }
 7541:                 }
 7542:                 if ($usec eq '') {
 7543:                     $usec = 'none';
 7544:                 }
 7545:                 if ($uname ne '' && $udom ne '') {
 7546:                     if ($hidepriv) {
 7547:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7548:                             (!$nothide{$uname.':'.$udom})) {
 7549:                             next;
 7550:                         }
 7551:                     }
 7552:                     if ($end > 0 && $end < $now) {
 7553:                         $status = 'previous';
 7554:                     } elsif ($start > $now) {
 7555:                         $status = 'future';
 7556:                     } else {
 7557:                         $status = 'active';
 7558:                     }
 7559:                     foreach my $type (keys(%{$types})) { 
 7560:                         if ($status eq $type) {
 7561:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7562:                                 push(@{$$users{$role}{$user}},$type);
 7563:                             }
 7564:                             $match = 1;
 7565:                         }
 7566:                     }
 7567:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7568:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7569: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7570:                         }
 7571:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7572:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7573:                         }
 7574:                         if (ref($statushash) eq 'HASH') {
 7575:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7576:                         }
 7577:                     }
 7578:                 }
 7579:             }
 7580:         }
 7581:         if (grep(/^ow$/,@{$roles})) {
 7582:             if ((defined($cdom)) && (defined($cnum))) {
 7583:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7584:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7585:                     my $owner = $csettings{'internal.courseowner'};
 7586:                     next if ($owner eq '');
 7587:                     my ($ownername,$ownerdom);
 7588:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7589:                         $ownername = $1;
 7590:                         $ownerdom = $2;
 7591:                     } else {
 7592:                         $ownername = $owner;
 7593:                         $ownerdom = $cdom;
 7594:                         $owner = $ownername.':'.$ownerdom;
 7595:                     }
 7596:                     @{$$users{'ow'}{$owner}} = 'any';
 7597:                     if (defined($userdata) && 
 7598: 			!exists($$userdata{$owner})) {
 7599: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7600:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7601:                             push(@{$seclists{$owner}},'none');
 7602:                         }
 7603:                         if (ref($statushash) eq 'HASH') {
 7604:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7605:                         }
 7606: 		    }
 7607:                 }
 7608:             }
 7609:         }
 7610:         foreach my $user (keys(%seclists)) {
 7611:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7612:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7613:         }
 7614:     }
 7615:     return;
 7616: }
 7617: 
 7618: sub get_user_info {
 7619:     my ($udom,$uname,$idx,$userdata) = @_;
 7620:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7621: 	&plainname($uname,$udom,'lastname');
 7622:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7623:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7624:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7625:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7626:     return;
 7627: }
 7628: 
 7629: ###############################################
 7630: 
 7631: =pod
 7632: 
 7633: =item * &get_user_quota()
 7634: 
 7635: Retrieves quota assigned for storage of portfolio files for a user  
 7636: 
 7637: Incoming parameters:
 7638: 1. user's username
 7639: 2. user's domain
 7640: 
 7641: Returns:
 7642: 1. Disk quota (in Mb) assigned to student.
 7643: 2. (Optional) Type of setting: custom or default
 7644:    (individually assigned or default for user's 
 7645:    institutional status).
 7646: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7647:    or student - types as defined in localenroll::inst_usertypes 
 7648:    for user's domain, which determines default quota for user.
 7649: 4. (Optional) - Default quota which would apply to the user.
 7650: 
 7651: If a value has been stored in the user's environment, 
 7652: it will return that, otherwise it returns the maximal default
 7653: defined for the user's instituional status(es) in the domain.
 7654: 
 7655: =cut
 7656: 
 7657: ###############################################
 7658: 
 7659: 
 7660: sub get_user_quota {
 7661:     my ($uname,$udom) = @_;
 7662:     my ($quota,$quotatype,$settingstatus,$defquota);
 7663:     if (!defined($udom)) {
 7664:         $udom = $env{'user.domain'};
 7665:     }
 7666:     if (!defined($uname)) {
 7667:         $uname = $env{'user.name'};
 7668:     }
 7669:     if (($udom eq '' || $uname eq '') ||
 7670:         ($udom eq 'public') && ($uname eq 'public')) {
 7671:         $quota = 0;
 7672:         $quotatype = 'default';
 7673:         $defquota = 0; 
 7674:     } else {
 7675:         my $inststatus;
 7676:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7677:             $quota = $env{'environment.portfolioquota'};
 7678:             $inststatus = $env{'environment.inststatus'};
 7679:         } else {
 7680:             my %userenv = 
 7681:                 &Apache::lonnet::get('environment',['portfolioquota',
 7682:                                      'inststatus'],$udom,$uname);
 7683:             my ($tmp) = keys(%userenv);
 7684:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7685:                 $quota = $userenv{'portfolioquota'};
 7686:                 $inststatus = $userenv{'inststatus'};
 7687:             } else {
 7688:                 undef(%userenv);
 7689:             }
 7690:         }
 7691:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7692:         if ($quota eq '') {
 7693:             $quota = $defquota;
 7694:             $quotatype = 'default';
 7695:         } else {
 7696:             $quotatype = 'custom';
 7697:         }
 7698:     }
 7699:     if (wantarray) {
 7700:         return ($quota,$quotatype,$settingstatus,$defquota);
 7701:     } else {
 7702:         return $quota;
 7703:     }
 7704: }
 7705: 
 7706: ###############################################
 7707: 
 7708: =pod
 7709: 
 7710: =item * &default_quota()
 7711: 
 7712: Retrieves default quota assigned for storage of user portfolio files,
 7713: given an (optional) user's institutional status.
 7714: 
 7715: Incoming parameters:
 7716: 1. domain
 7717: 2. (Optional) institutional status(es).  This is a : separated list of 
 7718:    status types (e.g., faculty, staff, student etc.)
 7719:    which apply to the user for whom the default is being retrieved.
 7720:    If the institutional status string in undefined, the domain
 7721:    default quota will be returned. 
 7722: 
 7723: Returns:
 7724: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7725: 2. (Optional) institutional type which determined the value of the
 7726:    default quota.
 7727: 
 7728: If a value has been stored in the domain's configuration db,
 7729: it will return that, otherwise it returns 20 (for backwards 
 7730: compatibility with domains which have not set up a configuration
 7731: db file; the original statically defined portfolio quota was 20 Mb). 
 7732: 
 7733: If the user's status includes multiple types (e.g., staff and student),
 7734: the largest default quota which applies to the user determines the
 7735: default quota returned.
 7736: 
 7737: =back
 7738: 
 7739: =cut
 7740: 
 7741: ###############################################
 7742: 
 7743: 
 7744: sub default_quota {
 7745:     my ($udom,$inststatus) = @_;
 7746:     my ($defquota,$settingstatus);
 7747:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7748:                                             ['quotas'],$udom);
 7749:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7750:         if ($inststatus ne '') {
 7751:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7752:             foreach my $item (@statuses) {
 7753:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7754:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7755:                         if ($defquota eq '') {
 7756:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7757:                             $settingstatus = $item;
 7758:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7759:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7760:                             $settingstatus = $item;
 7761:                         }
 7762:                     }
 7763:                 } else {
 7764:                     if ($quotahash{'quotas'}{$item} ne '') {
 7765:                         if ($defquota eq '') {
 7766:                             $defquota = $quotahash{'quotas'}{$item};
 7767:                             $settingstatus = $item;
 7768:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7769:                             $defquota = $quotahash{'quotas'}{$item};
 7770:                             $settingstatus = $item;
 7771:                         }
 7772:                     }
 7773:                 }
 7774:             }
 7775:         }
 7776:         if ($defquota eq '') {
 7777:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7778:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7779:             } else {
 7780:                 $defquota = $quotahash{'quotas'}{'default'};
 7781:             }
 7782:             $settingstatus = 'default';
 7783:         }
 7784:     } else {
 7785:         $settingstatus = 'default';
 7786:         $defquota = 20;
 7787:     }
 7788:     if (wantarray) {
 7789:         return ($defquota,$settingstatus);
 7790:     } else {
 7791:         return $defquota;
 7792:     }
 7793: }
 7794: 
 7795: sub get_secgrprole_info {
 7796:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7797:     my %sections_count = &get_sections($cdom,$cnum);
 7798:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7799:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7800:     my @groups = sort(keys(%curr_groups));
 7801:     my $allroles = [];
 7802:     my $rolehash;
 7803:     my $accesshash = {
 7804:                      active => 'Currently has access',
 7805:                      future => 'Will have future access',
 7806:                      previous => 'Previously had access',
 7807:                   };
 7808:     if ($needroles) {
 7809:         $rolehash = {'all' => 'all'};
 7810:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7811: 	if (&Apache::lonnet::error(%user_roles)) {
 7812: 	    undef(%user_roles);
 7813: 	}
 7814:         foreach my $item (keys(%user_roles)) {
 7815:             my ($role)=split(/\:/,$item,2);
 7816:             if ($role eq 'cr') { next; }
 7817:             if ($role =~ /^cr/) {
 7818:                 $$rolehash{$role} = (split('/',$role))[3];
 7819:             } else {
 7820:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7821:             }
 7822:         }
 7823:         foreach my $key (sort(keys(%{$rolehash}))) {
 7824:             push(@{$allroles},$key);
 7825:         }
 7826:         push (@{$allroles},'st');
 7827:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7828:     }
 7829:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7830: }
 7831: 
 7832: sub user_picker {
 7833:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 7834:     my $currdom = $dom;
 7835:     my %curr_selected = (
 7836:                         srchin => 'dom',
 7837:                         srchby => 'lastname',
 7838:                       );
 7839:     my $srchterm;
 7840:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7841:         if ($srch->{'srchby'} ne '') {
 7842:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7843:         }
 7844:         if ($srch->{'srchin'} ne '') {
 7845:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7846:         }
 7847:         if ($srch->{'srchtype'} ne '') {
 7848:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7849:         }
 7850:         if ($srch->{'srchdomain'} ne '') {
 7851:             $currdom = $srch->{'srchdomain'};
 7852:         }
 7853:         $srchterm = $srch->{'srchterm'};
 7854:     }
 7855:     my %lt=&Apache::lonlocal::texthash(
 7856:                     'usr'       => 'Search criteria',
 7857:                     'doma'      => 'Domain/institution to search',
 7858:                     'uname'     => 'username',
 7859:                     'lastname'  => 'last name',
 7860:                     'lastfirst' => 'last name, first name',
 7861:                     'crs'       => 'in this course',
 7862:                     'dom'       => 'in selected LON-CAPA domain', 
 7863:                     'alc'       => 'all LON-CAPA',
 7864:                     'instd'     => 'in institutional directory for selected domain',
 7865:                     'exact'     => 'is',
 7866:                     'contains'  => 'contains',
 7867:                     'begins'    => 'begins with',
 7868:                     'youm'      => "You must include some text to search for.",
 7869:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7870:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7871:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7872:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7873:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7874:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7875:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7876:                                        );
 7877:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7878:     my $srchinsel = ' <select name="srchin">';
 7879: 
 7880:     my @srchins = ('crs','dom','alc','instd');
 7881: 
 7882:     foreach my $option (@srchins) {
 7883:         # FIXME 'alc' option unavailable until 
 7884:         #       loncreateuser::print_user_query_page()
 7885:         #       has been completed.
 7886:         next if ($option eq 'alc');
 7887:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7888:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7889:         if ($curr_selected{'srchin'} eq $option) {
 7890:             $srchinsel .= ' 
 7891:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7892:         } else {
 7893:             $srchinsel .= '
 7894:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7895:         }
 7896:     }
 7897:     $srchinsel .= "\n  </select>\n";
 7898: 
 7899:     my $srchbysel =  ' <select name="srchby">';
 7900:     foreach my $option ('lastname','lastfirst','uname') {
 7901:         if ($curr_selected{'srchby'} eq $option) {
 7902:             $srchbysel .= '
 7903:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7904:         } else {
 7905:             $srchbysel .= '
 7906:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7907:          }
 7908:     }
 7909:     $srchbysel .= "\n  </select>\n";
 7910: 
 7911:     my $srchtypesel = ' <select name="srchtype">';
 7912:     foreach my $option ('begins','contains','exact') {
 7913:         if ($curr_selected{'srchtype'} eq $option) {
 7914:             $srchtypesel .= '
 7915:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7916:         } else {
 7917:             $srchtypesel .= '
 7918:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7919:         }
 7920:     }
 7921:     $srchtypesel .= "\n  </select>\n";
 7922: 
 7923:     my ($newuserscript,$new_user_create);
 7924:     my $context_dom = $env{'request.role.domain'};
 7925:     if ($context eq 'requestcrs') {
 7926:         if ($env{'form.coursedom'} ne '') {
 7927:             $context_dom = $env{'form.coursedom'};
 7928:         }
 7929:     }
 7930:     if ($forcenewuser) {
 7931:         if (ref($srch) eq 'HASH') {
 7932:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 7933:                 if ($cancreate) {
 7934:                     $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>';
 7935:                 } else {
 7936:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7937:                     my %usertypetext = (
 7938:                         official   => 'institutional',
 7939:                         unofficial => 'non-institutional',
 7940:                     );
 7941:                     $new_user_create = '<p class="LC_warning">'
 7942:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7943:                                       .' '
 7944:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7945:                                           ,'<a href="'.$helplink.'">','</a>')
 7946:                                       .'</p><br />';
 7947:                 }
 7948:             }
 7949:         }
 7950: 
 7951:         $newuserscript = <<"ENDSCRIPT";
 7952: 
 7953: function setSearch(createnew,callingForm) {
 7954:     if (createnew == 1) {
 7955:         for (var i=0; i<callingForm.srchby.length; i++) {
 7956:             if (callingForm.srchby.options[i].value == 'uname') {
 7957:                 callingForm.srchby.selectedIndex = i;
 7958:             }
 7959:         }
 7960:         for (var i=0; i<callingForm.srchin.length; i++) {
 7961:             if ( callingForm.srchin.options[i].value == 'dom') {
 7962: 		callingForm.srchin.selectedIndex = i;
 7963:             }
 7964:         }
 7965:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7966:             if (callingForm.srchtype.options[i].value == 'exact') {
 7967:                 callingForm.srchtype.selectedIndex = i;
 7968:             }
 7969:         }
 7970:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7971:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 7972:                 callingForm.srchdomain.selectedIndex = i;
 7973:             }
 7974:         }
 7975:     }
 7976: }
 7977: ENDSCRIPT
 7978: 
 7979:     }
 7980: 
 7981:     my $output = <<"END_BLOCK";
 7982: <script type="text/javascript">
 7983: // <![CDATA[
 7984: function validateEntry(callingForm) {
 7985: 
 7986:     var checkok = 1;
 7987:     var srchin;
 7988:     for (var i=0; i<callingForm.srchin.length; i++) {
 7989: 	if ( callingForm.srchin[i].checked ) {
 7990: 	    srchin = callingForm.srchin[i].value;
 7991: 	}
 7992:     }
 7993: 
 7994:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7995:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7996:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7997:     var srchterm =  callingForm.srchterm.value;
 7998:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7999:     var msg = "";
 8000: 
 8001:     if (srchterm == "") {
 8002:         checkok = 0;
 8003:         msg += "$lt{'youm'}\\n";
 8004:     }
 8005: 
 8006:     if (srchtype== 'begins') {
 8007:         if (srchterm.length < 2) {
 8008:             checkok = 0;
 8009:             msg += "$lt{'thte'}\\n";
 8010:         }
 8011:     }
 8012: 
 8013:     if (srchtype== 'contains') {
 8014:         if (srchterm.length < 3) {
 8015:             checkok = 0;
 8016:             msg += "$lt{'thet'}\\n";
 8017:         }
 8018:     }
 8019:     if (srchin == 'instd') {
 8020:         if (srchdomain == '') {
 8021:             checkok = 0;
 8022:             msg += "$lt{'yomc'}\\n";
 8023:         }
 8024:     }
 8025:     if (srchin == 'dom') {
 8026:         if (srchdomain == '') {
 8027:             checkok = 0;
 8028:             msg += "$lt{'ymcd'}\\n";
 8029:         }
 8030:     }
 8031:     if (srchby == 'lastfirst') {
 8032:         if (srchterm.indexOf(",") == -1) {
 8033:             checkok = 0;
 8034:             msg += "$lt{'whus'}\\n";
 8035:         }
 8036:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8037:             checkok = 0;
 8038:             msg += "$lt{'whse'}\\n";
 8039:         }
 8040:     }
 8041:     if (checkok == 0) {
 8042:         alert("$lt{'thfo'}\\n"+msg);
 8043:         return;
 8044:     }
 8045:     if (checkok == 1) {
 8046:         callingForm.submit();
 8047:     }
 8048: }
 8049: 
 8050: $newuserscript
 8051: 
 8052: // ]]>
 8053: </script>
 8054: 
 8055: $new_user_create
 8056: 
 8057: END_BLOCK
 8058: 
 8059:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8060:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8061:                $domform.
 8062:                &Apache::lonhtmlcommon::row_closure().
 8063:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8064:                $srchbysel.
 8065:                $srchtypesel. 
 8066:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8067:                $srchinsel.
 8068:                &Apache::lonhtmlcommon::row_closure(1). 
 8069:                &Apache::lonhtmlcommon::end_pick_box().
 8070:                '<br />';
 8071:     return $output;
 8072: }
 8073: 
 8074: sub user_rule_check {
 8075:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8076:     my $response;
 8077:     if (ref($usershash) eq 'HASH') {
 8078:         foreach my $user (keys(%{$usershash})) {
 8079:             my ($uname,$udom) = split(/:/,$user);
 8080:             next if ($udom eq '' || $uname eq '');
 8081:             my ($id,$newuser);
 8082:             if (ref($usershash->{$user}) eq 'HASH') {
 8083:                 $newuser = $usershash->{$user}->{'newuser'};
 8084:                 $id = $usershash->{$user}->{'id'};
 8085:             }
 8086:             my $inst_response;
 8087:             if (ref($checks) eq 'HASH') {
 8088:                 if (defined($checks->{'username'})) {
 8089:                     ($inst_response,%{$inst_results->{$user}}) = 
 8090:                         &Apache::lonnet::get_instuser($udom,$uname);
 8091:                 } elsif (defined($checks->{'id'})) {
 8092:                     ($inst_response,%{$inst_results->{$user}}) =
 8093:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8094:                 }
 8095:             } else {
 8096:                 ($inst_response,%{$inst_results->{$user}}) =
 8097:                     &Apache::lonnet::get_instuser($udom,$uname);
 8098:                 return;
 8099:             }
 8100:             if (!$got_rules->{$udom}) {
 8101:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8102:                                                   ['usercreation'],$udom);
 8103:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8104:                     foreach my $item ('username','id') {
 8105:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8106:                             $$curr_rules{$udom}{$item} = 
 8107:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8108:                         }
 8109:                     }
 8110:                 }
 8111:                 $got_rules->{$udom} = 1;  
 8112:             }
 8113:             foreach my $item (keys(%{$checks})) {
 8114:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8115:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8116:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8117:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8118:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8119:                                 if ($rule_check{$rule}) {
 8120:                                     $$rulematch{$user}{$item} = $rule;
 8121:                                     if ($inst_response eq 'ok') {
 8122:                                         if (ref($inst_results) eq 'HASH') {
 8123:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8124:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8125:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8126:                                                 }
 8127:                                             }
 8128:                                         }
 8129:                                     }
 8130:                                     last;
 8131:                                 }
 8132:                             }
 8133:                         }
 8134:                     }
 8135:                 }
 8136:             }
 8137:         }
 8138:     }
 8139:     return;
 8140: }
 8141: 
 8142: sub user_rule_formats {
 8143:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8144:     my %text = ( 
 8145:                  'username' => 'Usernames',
 8146:                  'id'       => 'IDs',
 8147:                );
 8148:     my $output;
 8149:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8150:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8151:         if (@{$ruleorder} > 0) {
 8152:             $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>';
 8153:             foreach my $rule (@{$ruleorder}) {
 8154:                 if (ref($curr_rules) eq 'ARRAY') {
 8155:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8156:                         if (ref($rules->{$rule}) eq 'HASH') {
 8157:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8158:                                         $rules->{$rule}{'desc'}.'</li>';
 8159:                         }
 8160:                     }
 8161:                 }
 8162:             }
 8163:             $output .= '</ul>';
 8164:         }
 8165:     }
 8166:     return $output;
 8167: }
 8168: 
 8169: sub instrule_disallow_msg {
 8170:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8171:     my $response;
 8172:     my %text = (
 8173:                   item   => 'username',
 8174:                   items  => 'usernames',
 8175:                   match  => 'matches',
 8176:                   do     => 'does',
 8177:                   action => 'a username',
 8178:                   one    => 'one',
 8179:                );
 8180:     if ($count > 1) {
 8181:         $text{'item'} = 'usernames';
 8182:         $text{'match'} ='match';
 8183:         $text{'do'} = 'do';
 8184:         $text{'action'} = 'usernames',
 8185:         $text{'one'} = 'ones';
 8186:     }
 8187:     if ($checkitem eq 'id') {
 8188:         $text{'items'} = 'IDs';
 8189:         $text{'item'} = 'ID';
 8190:         $text{'action'} = 'an ID';
 8191:         if ($count > 1) {
 8192:             $text{'item'} = 'IDs';
 8193:             $text{'action'} = 'IDs';
 8194:         }
 8195:     }
 8196:     $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 />';
 8197:     if ($mode eq 'upload') {
 8198:         if ($checkitem eq 'username') {
 8199:             $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'}.");
 8200:         } elsif ($checkitem eq 'id') {
 8201:             $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.");
 8202:         }
 8203:     } elsif ($mode eq 'selfcreate') {
 8204:         if ($checkitem eq 'id') {
 8205:             $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.");
 8206:         }
 8207:     } else {
 8208:         if ($checkitem eq 'username') {
 8209:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8210:         } elsif ($checkitem eq 'id') {
 8211:             $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.");
 8212:         }
 8213:     }
 8214:     return $response;
 8215: }
 8216: 
 8217: sub personal_data_fieldtitles {
 8218:     my %fieldtitles = &Apache::lonlocal::texthash (
 8219:                         id => 'Student/Employee ID',
 8220:                         permanentemail => 'E-mail address',
 8221:                         lastname => 'Last Name',
 8222:                         firstname => 'First Name',
 8223:                         middlename => 'Middle Name',
 8224:                         generation => 'Generation',
 8225:                         gen => 'Generation',
 8226:                         inststatus => 'Affiliation',
 8227:                    );
 8228:     return %fieldtitles;
 8229: }
 8230: 
 8231: sub sorted_inst_types {
 8232:     my ($dom) = @_;
 8233:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8234:     my $othertitle = &mt('All users');
 8235:     if ($env{'request.course.id'}) {
 8236:         $othertitle  = &mt('Any users');
 8237:     }
 8238:     my @types;
 8239:     if (ref($order) eq 'ARRAY') {
 8240:         @types = @{$order};
 8241:     }
 8242:     if (@types == 0) {
 8243:         if (ref($usertypes) eq 'HASH') {
 8244:             @types = sort(keys(%{$usertypes}));
 8245:         }
 8246:     }
 8247:     if (keys(%{$usertypes}) > 0) {
 8248:         $othertitle = &mt('Other users');
 8249:     }
 8250:     return ($othertitle,$usertypes,\@types);
 8251: }
 8252: 
 8253: sub get_institutional_codes {
 8254:     my ($settings,$allcourses,$LC_code) = @_;
 8255: # Get complete list of course sections to update
 8256:     my @currsections = ();
 8257:     my @currxlists = ();
 8258:     my $coursecode = $$settings{'internal.coursecode'};
 8259: 
 8260:     if ($$settings{'internal.sectionnums'} ne '') {
 8261:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8262:     }
 8263: 
 8264:     if ($$settings{'internal.crosslistings'} ne '') {
 8265:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8266:     }
 8267: 
 8268:     if (@currxlists > 0) {
 8269:         foreach (@currxlists) {
 8270:             if (m/^([^:]+):(\w*)$/) {
 8271:                 unless (grep/^$1$/,@{$allcourses}) {
 8272:                     push @{$allcourses},$1;
 8273:                     $$LC_code{$1} = $2;
 8274:                 }
 8275:             }
 8276:         }
 8277:     }
 8278:  
 8279:     if (@currsections > 0) {
 8280:         foreach (@currsections) {
 8281:             if (m/^(\w+):(\w*)$/) {
 8282:                 my $sec = $coursecode.$1;
 8283:                 my $lc_sec = $2;
 8284:                 unless (grep/^$sec$/,@{$allcourses}) {
 8285:                     push @{$allcourses},$sec;
 8286:                     $$LC_code{$sec} = $lc_sec;
 8287:                 }
 8288:             }
 8289:         }
 8290:     }
 8291:     return;
 8292: }
 8293: 
 8294: sub get_standard_codeitems {
 8295:     return ('Year','Semester','Department','Number','Section');
 8296: }
 8297: 
 8298: =pod
 8299: 
 8300: =head1 Slot Helpers
 8301: 
 8302: =over 4
 8303: 
 8304: =item * sorted_slots()
 8305: 
 8306: Sorts an array of slot names in order of slot start time (earliest first). 
 8307: 
 8308: Inputs:
 8309: 
 8310: =over 4
 8311: 
 8312: slotsarr  - Reference to array of unsorted slot names.
 8313: 
 8314: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8315: 
 8316: =back
 8317: 
 8318: Returns:
 8319: 
 8320: =over 4
 8321: 
 8322: sorted   - An array of slot names sorted by the start time of the slot.
 8323: 
 8324: =back
 8325: 
 8326: =back
 8327: 
 8328: =cut
 8329: 
 8330: 
 8331: sub sorted_slots {
 8332:     my ($slotsarr,$slots) = @_;
 8333:     my @sorted;
 8334:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8335:         @sorted =
 8336:             sort {
 8337:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8338:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8339:                      }
 8340:                      if (ref($slots->{$a})) { return -1;}
 8341:                      if (ref($slots->{$b})) { return 1;}
 8342:                      return 0;
 8343:                  } @{$slotsarr};
 8344:     }
 8345:     return @sorted;
 8346: }
 8347: 
 8348: 
 8349: =pod
 8350: 
 8351: =head1 HTTP Helpers
 8352: 
 8353: =over 4
 8354: 
 8355: =item * &get_unprocessed_cgi($query,$possible_names)
 8356: 
 8357: Modify the %env hash to contain unprocessed CGI form parameters held in
 8358: $query.  The parameters listed in $possible_names (an array reference),
 8359: will be set in $env{'form.name'} if they do not already exist.
 8360: 
 8361: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8362: $possible_names is an ref to an array of form element names.  As an example:
 8363: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8364: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8365: 
 8366: =cut
 8367: 
 8368: sub get_unprocessed_cgi {
 8369:   my ($query,$possible_names)= @_;
 8370:   # $Apache::lonxml::debug=1;
 8371:   foreach my $pair (split(/&/,$query)) {
 8372:     my ($name, $value) = split(/=/,$pair);
 8373:     $name = &unescape($name);
 8374:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8375:       $value =~ tr/+/ /;
 8376:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8377:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8378:     }
 8379:   }
 8380: }
 8381: 
 8382: =pod
 8383: 
 8384: =item * &cacheheader() 
 8385: 
 8386: returns cache-controlling header code
 8387: 
 8388: =cut
 8389: 
 8390: sub cacheheader {
 8391:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8392:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8393:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8394:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8395:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8396:     return $output;
 8397: }
 8398: 
 8399: =pod
 8400: 
 8401: =item * &no_cache($r) 
 8402: 
 8403: specifies header code to not have cache
 8404: 
 8405: =cut
 8406: 
 8407: sub no_cache {
 8408:     my ($r) = @_;
 8409:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8410: 	$env{'request.method'} ne 'GET') { return ''; }
 8411:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8412:     $r->no_cache(1);
 8413:     $r->header_out("Expires" => $date);
 8414:     $r->header_out("Pragma" => "no-cache");
 8415: }
 8416: 
 8417: sub content_type {
 8418:     my ($r,$type,$charset) = @_;
 8419:     if ($r) {
 8420: 	#  Note that printout.pl calls this with undef for $r.
 8421: 	&no_cache($r);
 8422:     }
 8423:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8424:     unless ($charset) {
 8425: 	$charset=&Apache::lonlocal::current_encoding;
 8426:     }
 8427:     if ($charset) { $type.='; charset='.$charset; }
 8428:     if ($r) {
 8429: 	$r->content_type($type);
 8430:     } else {
 8431: 	print("Content-type: $type\n\n");
 8432:     }
 8433: }
 8434: 
 8435: =pod
 8436: 
 8437: =item * &add_to_env($name,$value) 
 8438: 
 8439: adds $name to the %env hash with value
 8440: $value, if $name already exists, the entry is converted to an array
 8441: reference and $value is added to the array.
 8442: 
 8443: =cut
 8444: 
 8445: sub add_to_env {
 8446:   my ($name,$value)=@_;
 8447:   if (defined($env{$name})) {
 8448:     if (ref($env{$name})) {
 8449:       #already have multiple values
 8450:       push(@{ $env{$name} },$value);
 8451:     } else {
 8452:       #first time seeing multiple values, convert hash entry to an arrayref
 8453:       my $first=$env{$name};
 8454:       undef($env{$name});
 8455:       push(@{ $env{$name} },$first,$value);
 8456:     }
 8457:   } else {
 8458:     $env{$name}=$value;
 8459:   }
 8460: }
 8461: 
 8462: =pod
 8463: 
 8464: =item * &get_env_multiple($name) 
 8465: 
 8466: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8467: values may be defined and end up as an array ref.
 8468: 
 8469: returns an array of values
 8470: 
 8471: =cut
 8472: 
 8473: sub get_env_multiple {
 8474:     my ($name) = @_;
 8475:     my @values;
 8476:     if (defined($env{$name})) {
 8477:         # exists is it an array
 8478:         if (ref($env{$name})) {
 8479:             @values=@{ $env{$name} };
 8480:         } else {
 8481:             $values[0]=$env{$name};
 8482:         }
 8483:     }
 8484:     return(@values);
 8485: }
 8486: 
 8487: sub ask_for_embedded_content {
 8488:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8489:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
 8490:     my $num = 0;
 8491:     my $numremref = 0;
 8492:     my $numinvalid = 0;
 8493:     my $numpathchg = 0;
 8494:     my $numexisting = 0;
 8495:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
 8496:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8497:         my $current_path='/';
 8498:         if ($env{'form.currentpath'}) {
 8499:             $current_path = $env{'form.currentpath'};
 8500:         }
 8501:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 8502:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8503:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 8504:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 8505:         } else {
 8506:             $udom = $env{'user.domain'};
 8507:             $uname = $env{'user.name'};
 8508:             $url = '/userfiles/portfolio';
 8509:         }
 8510:         $toplevel = $url.'/';
 8511:         $url .= $current_path;
 8512:         $getpropath = 1;
 8513:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8514:              ($actionurl eq '/adm/imsimport')) {
 8515:         ($uname,my $rest) = ($args->{'current_path'} =~ m{/priv/($match_username)/?(.*)$});
 8516:         $url = '/home/'.$uname.'/public_html/';
 8517:         $toplevel = $url;
 8518:         if ($rest ne '') {
 8519:             $url .= $rest;
 8520:         }
 8521:     } elsif ($actionurl eq '/adm/coursedocs') {
 8522:         if (ref($args) eq 'HASH') {
 8523:            $url = $args->{'docs_url'};
 8524:            $toplevel = $url;
 8525:         }
 8526:     }
 8527:     my $now = time();
 8528:     foreach my $embed_file (keys(%{$allfiles})) {
 8529:         my $absolutepath;
 8530:         if ($embed_file =~ m{^\w+://}) {
 8531:             $newfiles{$embed_file} = 1;
 8532:             $mapping{$embed_file} = $embed_file;
 8533:         } else {
 8534:             if ($embed_file =~ m{^/}) {
 8535:                 $absolutepath = $embed_file;
 8536:                 $embed_file =~ s{^(/+)}{};
 8537:             }
 8538:             if ($embed_file =~ m{/}) {
 8539:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 8540:                 $path = &check_for_traversal($path,$url,$toplevel);
 8541:                 my $item = $fname;
 8542:                 if ($path ne '') {
 8543:                     $item = $path.'/'.$fname;
 8544:                     $subdependencies{$path}{$fname} = 1;
 8545:                 } else {
 8546:                     $dependencies{$item} = 1;
 8547:                 }
 8548:                 if ($absolutepath) {
 8549:                     $mapping{$item} = $absolutepath;
 8550:                 } else {
 8551:                     $mapping{$item} = $embed_file;
 8552:                 }
 8553:             } else {
 8554:                 $dependencies{$embed_file} = 1;
 8555:                 if ($absolutepath) {
 8556:                     $mapping{$embed_file} = $absolutepath;
 8557:                 } else {
 8558:                     $mapping{$embed_file} = $embed_file;
 8559:                 }
 8560:             }
 8561:         }
 8562:     }
 8563:     foreach my $path (keys(%subdependencies)) {
 8564:         my %currsubfile;
 8565:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8566:             my @subdir_list = &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 8567:             foreach my $line (@subdir_list) {
 8568:                 my ($file_name,$rest) = split(/\&/,$line,2);
 8569:                 $currsubfile{$file_name} = 1;
 8570:             }
 8571:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8572:             if (opendir(my $dir,$url.'/'.$path)) {
 8573:                 my @subdir_list = grep(!/^\./,readdir($dir));
 8574:                 map {$currsubfile{$_} = 1;} @subdir_list;
 8575:             }
 8576:         }
 8577:         foreach my $file (keys(%{$subdependencies{$path}})) {
 8578:             if ($currsubfile{$file}) {
 8579:                 my $item = $path.'/'.$file;
 8580:                 unless ($mapping{$item} eq $item) {
 8581:                     $pathchanges{$item} = 1;
 8582:                 }
 8583:                 $existing{$item} = 1;
 8584:                 $numexisting ++;
 8585:             } else {
 8586:                 $newfiles{$path.'/'.$file} = 1;
 8587:             }
 8588:         }
 8589:     }
 8590:     my %currfile;
 8591:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8592:         my @dir_list = &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 8593:         foreach my $line (@dir_list) {
 8594:             my ($file_name,$rest) = split(/\&/,$line,2);
 8595:             $currfile{$file_name} = 1;
 8596:         }
 8597:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8598:         if (opendir(my $dir,$url)) {
 8599:             my @dir_list = grep(!/^\./,readdir($dir));
 8600:             map {$currfile{$_} = 1;} @dir_list;
 8601:         }
 8602:     }
 8603:     foreach my $file (keys(%dependencies)) {
 8604:         if ($currfile{$file}) {
 8605:             unless ($mapping{$file} eq $file) {
 8606:                 $pathchanges{$file} = 1;
 8607:             }
 8608:             $existing{$file} = 1;
 8609:             $numexisting ++;
 8610:         } else {
 8611:             $newfiles{$file} = 1;
 8612:         }
 8613:     }
 8614:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 8615:         $upload_output .= &start_data_table_row().
 8616:                           '<td><span class="LC_filename">'.$embed_file.'</span>';
 8617:         unless ($mapping{$embed_file} eq $embed_file) {
 8618:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 8619:         }
 8620:         $upload_output .= '</td><td>';
 8621:         if ($args->{'ignore_remote_references'}
 8622:             && $embed_file =~ m{^\w+://}) {
 8623:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8624:             $numremref++;
 8625:         } elsif ($args->{'error_on_invalid_names'}
 8626:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8627: 
 8628:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 8629:             $numinvalid++;
 8630:         } else {
 8631:             $upload_output .= &embedded_file_element('upload_embedded',$num,
 8632:                                                      $embed_file,\%mapping,
 8633:                                                      $allfiles,$codebase);
 8634:             $num++;
 8635:         }
 8636:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 8637:     }
 8638:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 8639:         $upload_output .= &start_data_table_row().
 8640:                           '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
 8641:                           '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 8642:                           &Apache::loncommon::end_data_table_row()."\n";
 8643:     }
 8644:     if ($upload_output) {
 8645:         $upload_output = &start_data_table().
 8646:                          $upload_output.
 8647:                          &end_data_table()."\n";
 8648:     }
 8649:     my $applies = 0;
 8650:     if ($numremref) {
 8651:         $applies ++;
 8652:     }
 8653:     if ($numinvalid) {
 8654:         $applies ++;
 8655:     }
 8656:     if ($numexisting) {
 8657:         $applies ++;
 8658:     }
 8659:     if ($num) {
 8660:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 8661:                   ' method="post" enctype="multipart/form-data">'."\n".
 8662:                   $state.
 8663:                   '<h3>'.&mt('Upload embedded files').
 8664:                   ':</h3>'.$upload_output.'<br />'."\n".
 8665:                   '<input type ="hidden" name="number_embedded_items" value="'.
 8666:                   $num.'" />'."\n";
 8667:         if ($actionurl eq '') {
 8668:             $output .=  '<input type="hidden" name="phase" value="three" />';
 8669:         }
 8670:     } elsif ($applies) {
 8671:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 8672:         if ($applies > 1) {
 8673:             $output .=
 8674:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 8675:             if ($numremref) {
 8676:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 8677:             }
 8678:             if ($numinvalid) {
 8679:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 8680:             }
 8681:             if ($numexisting) {
 8682:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 8683:             }
 8684:             $output .= '</ul><br />';
 8685:         } elsif ($numremref) {
 8686:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 8687:         } elsif ($numinvalid) {
 8688:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 8689:         } elsif ($numexisting) {
 8690:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 8691:         }
 8692:         $output .= $upload_output.'<br />';
 8693:     }
 8694:     my ($pathchange_output,$chgcount);
 8695:     $chgcount = $num;
 8696:     if (keys(%pathchanges) > 0) {
 8697:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 8698:             if ($num) {
 8699:                 $output .= &embedded_file_element('pathchange',$chgcount,
 8700:                                                   $embed_file,\%mapping,
 8701:                                                   $allfiles,$codebase);
 8702:             } else {
 8703:                 $pathchange_output .=
 8704:                     &start_data_table_row().
 8705:                     '<td><input type ="checkbox" name="namechange" value="'.
 8706:                     $chgcount.'" checked="checked" /></td>'.
 8707:                     '<td>'.$mapping{$embed_file}.'</td>'.
 8708:                     '<td>'.$embed_file.
 8709:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 8710:                                            \%mapping,$allfiles,$codebase).
 8711:                     '</td>'.&end_data_table_row();
 8712:             }
 8713:             $numpathchg ++;
 8714:             $chgcount ++;
 8715:         }
 8716:     }
 8717:     if ($num) {
 8718:         if ($numpathchg) {
 8719:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 8720:                        $numpathchg.'" />'."\n";
 8721:         }
 8722:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8723:             ($actionurl eq '/adm/imsimport')) {
 8724:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 8725:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 8726:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 8727:         }
 8728:         $output .=  '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
 8729:                     &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
 8730:     } elsif ($numpathchg) {
 8731:         my %pathchange = ();
 8732:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 8733:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8734:             $output .= '<p>'.&mt('or').'</p>';
 8735:         }
 8736:     }
 8737:     return ($output,$num,$numpathchg);
 8738: }
 8739: 
 8740: sub embedded_file_element {
 8741:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
 8742:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 8743:                    (ref($codebase) eq 'HASH'));
 8744:     my $output;
 8745:     if ($context eq 'upload_embedded') {
 8746:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 8747:     }
 8748:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 8749:                &escape($embed_file).'" />';
 8750:     unless (($context eq 'upload_embedded') &&
 8751:             ($mapping->{$embed_file} eq $embed_file)) {
 8752:         $output .='
 8753:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 8754:     }
 8755:     my $attrib;
 8756:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 8757:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 8758:     }
 8759:     $output .=
 8760:         "\n\t\t".
 8761:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8762:         $attrib.'" />';
 8763:     if (exists($codebase->{$mapping->{$embed_file}})) {
 8764:         $output .=
 8765:             "\n\t\t".
 8766:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 8767:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 8768:     }
 8769:     return $output;
 8770: }
 8771: 
 8772: sub upload_embedded {
 8773:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8774:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 8775:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 8776:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8777:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8778:         my $orig_uploaded_filename =
 8779:             $env{'form.embedded_item_'.$i.'.filename'};
 8780:         foreach my $type ('orig','ref','attrib','codebase') {
 8781:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 8782:                 $env{'form.embedded_'.$type.'_'.$i} =
 8783:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 8784:             }
 8785:         }
 8786:         my ($path,$fname) =
 8787:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8788:         # no path, whole string is fname
 8789:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8790:         $fname = &Apache::lonnet::clean_filename($fname);
 8791:         # See if there is anything left
 8792:         next if ($fname eq '');
 8793: 
 8794:         # Check if file already exists as a file or directory.
 8795:         my ($state,$msg);
 8796:         if ($context eq 'portfolio') {
 8797:             my $port_path = $dirpath;
 8798:             if ($group ne '') {
 8799:                 $port_path = "groups/$group/$port_path";
 8800:             }
 8801:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 8802:                                               $fname,$group,'embedded_item_'.$i,
 8803:                                               $dir_root,$port_path,$disk_quota,
 8804:                                               $current_disk_usage,$uname,$udom);
 8805:             if ($state eq 'will_exceed_quota'
 8806:                 || $state eq 'file_locked') {
 8807:                 $output .= $msg;
 8808:                 next;
 8809:             }
 8810:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8811:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8812:             if ($state eq 'exists') {
 8813:                 $output .= $msg;
 8814:                 next;
 8815:             }
 8816:         }
 8817:         # Check if extension is valid
 8818:         if (($fname =~ /\.(\w+)$/) &&
 8819:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8820:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 8821:             next;
 8822:         } elsif (($fname =~ /\.(\w+)$/) &&
 8823:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8824:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 8825:             next;
 8826:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8827:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 8828:             next;
 8829:         }
 8830: 
 8831:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8832:         if ($context eq 'portfolio') {
 8833:             my $result;
 8834:             if ($state eq 'existingfile') {
 8835:                 $result=
 8836:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
 8837:                                                     $dirpath.$env{'form.currentpath'}.$path);
 8838:             } else {
 8839:                 $result=
 8840:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8841:                                                     $dirpath.
 8842:                                                     $env{'form.currentpath'}.$path);
 8843:                 if ($result !~ m|^/uploaded/|) {
 8844:                     $output .= '<span class="LC_error">'
 8845:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8846:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8847:                                .'</span><br />';
 8848:                     next;
 8849:                 } else {
 8850:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8851:                                $path.$fname.'</span>').'<br />'; 
 8852:                 }
 8853:             }
 8854:         } elsif ($context eq 'coursedoc') {
 8855:             my $result =
 8856:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
 8857:                                                 $dirpath.'/'.$path);
 8858:             if ($result !~ m|^/uploaded/|) {
 8859:                 $output .= '<span class="LC_error">'
 8860:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8861:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8862:                            .'</span><br />';
 8863:                     next;
 8864:             } else {
 8865:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8866:                            $path.$fname.'</span>').'<br />';
 8867:             }
 8868:         } else {
 8869: # Save the file
 8870:             my $target = $env{'form.embedded_item_'.$i};
 8871:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8872:             my $dest = $fullpath.$fname;
 8873:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8874:             my @parts=split(/\//,$fullpath);
 8875:             my $count;
 8876:             my $filepath = $dir_root;
 8877:             for ($count=4;$count<=$#parts;$count++) {
 8878:                 $filepath .= "/$parts[$count]";
 8879:                 if ((-e $filepath)!=1) {
 8880:                     mkdir($filepath,0770);
 8881:                 }
 8882:             }
 8883:             my $fh;
 8884:             if (!open($fh,'>'.$dest)) {
 8885:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8886:                 $output .= '<span class="LC_error">'.
 8887:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8888:                            '</span><br />';
 8889:             } else {
 8890:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8891:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8892:                     $output .= '<span class="LC_error">'.
 8893:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8894:                               '</span><br />';
 8895:                 } else {
 8896:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8897:                                $url.'</span>').'<br />';
 8898:                     unless ($context eq 'testbank') {
 8899:                         $footer .= &mt('View embedded file: [_1]',
 8900:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
 8901:                     }
 8902:                 }
 8903:                 close($fh);
 8904:             }
 8905:         }
 8906:         if ($env{'form.embedded_ref_'.$i}) {
 8907:             $pathchange{$i} = 1;
 8908:         }
 8909:     }
 8910:     if ($output) {
 8911:         $output = '<p>'.$output.'</p>';
 8912:     }
 8913:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
 8914:     $returnflag = 'ok';
 8915:     if (keys(%pathchange) > 0) {
 8916:         if ($context eq 'portfolio') {
 8917:             $output .= '<p>'.&mt('or').'</p>';
 8918:         } elsif ($context eq 'testbank') {
 8919:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
 8920:             $returnflag = 'modify_orightml';
 8921:         }
 8922:     }
 8923:     return ($output.$footer,$returnflag);
 8924: }
 8925: 
 8926: sub modify_html_form {
 8927:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
 8928:     my $end = 0;
 8929:     my $modifyform;
 8930:     if ($context eq 'upload_embedded') {
 8931:         return unless (ref($pathchange) eq 'HASH');
 8932:         if ($env{'form.number_embedded_items'}) {
 8933:             $end += $env{'form.number_embedded_items'};
 8934:         }
 8935:         if ($env{'form.number_pathchange_items'}) {
 8936:             $end += $env{'form.number_pathchange_items'};
 8937:         }
 8938:         if ($end) {
 8939:             for (my $i=0; $i<$end; $i++) {
 8940:                 if ($i < $env{'form.number_embedded_items'}) {
 8941:                     next unless($pathchange->{$i});
 8942:                 }
 8943:                 $modifyform .=
 8944:                     &start_data_table_row().
 8945:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
 8946:                     'checked="checked" /></td>'.
 8947:                     '<td>'.$env{'form.embedded_ref_'.$i}.
 8948:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
 8949:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
 8950:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
 8951:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
 8952:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
 8953:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
 8954:                     '<td>'.$env{'form.embedded_orig_'.$i}.
 8955:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
 8956:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
 8957:                     &end_data_table_row();
 8958:             }
 8959:         }
 8960:     } else {
 8961:         $modifyform = $pathchgtable;
 8962:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8963:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
 8964:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8965:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
 8966:         }
 8967:     }
 8968:     if ($modifyform) {
 8969:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
 8970:                '<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".
 8971:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
 8972:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
 8973:                '</ol></p>'."\n".'<p>'.
 8974:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
 8975:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
 8976:                &start_data_table()."\n".
 8977:                &start_data_table_header_row().
 8978:                '<th>'.&mt('Change?').'</th>'.
 8979:                '<th>'.&mt('Current reference').'</th>'.
 8980:                '<th>'.&mt('Required reference').'</th>'.
 8981:                &end_data_table_header_row()."\n".
 8982:                $modifyform.
 8983:                &end_data_table().'<br />'."\n".$hiddenstate.
 8984:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
 8985:                '</form>'."\n";
 8986:     }
 8987:     return;
 8988: }
 8989: 
 8990: sub modify_html_refs {
 8991:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
 8992:     my $container;
 8993:     if ($context eq 'portfolio') {
 8994:         $container = $env{'form.container'};
 8995:     } elsif ($context eq 'coursedoc') {
 8996:         $container = $env{'form.primaryurl'};
 8997:     } else {
 8998:         $container = $env{'form.filename'};
 8999:         $container =~ s{^/priv/(\Q$uname\E)/(.*)}{/home/$1/public_html/$2};
 9000:     }
 9001:     my (%allfiles,%codebase,$output,$content);
 9002:     my @changes = &get_env_multiple('form.namechange');
 9003:     return unless (@changes > 0);
 9004:     if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
 9005:         return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
 9006:         $content = &Apache::lonnet::getfile($container);
 9007:         return if ($content eq '-1');
 9008:     } else {
 9009:         return unless ($container =~ /^\Q$dir_root\E/);
 9010:         if (open(my $fh,"<$container")) {
 9011:             $content = join('', <$fh>);
 9012:             close($fh);
 9013:         } else {
 9014:             return;
 9015:         }
 9016:     }
 9017:     my ($count,$codebasecount) = (0,0);
 9018:     my $mm = new File::MMagic;
 9019:     my $mime_type = $mm->checktype_contents($content);
 9020:     if ($mime_type eq 'text/html') {
 9021:         my $parse_result =
 9022:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
 9023:                                                     \%codebase,\$content);
 9024:         if ($parse_result eq 'ok') {
 9025:             foreach my $i (@changes) {
 9026:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
 9027:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
 9028:                 if ($allfiles{$ref}) {
 9029:                     my $newname =  $orig;
 9030:                     my ($attrib_regexp,$codebase);
 9031:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
 9032:                     if ($attrib_regexp =~ /:/) {
 9033:                         $attrib_regexp =~ s/\:/|/g;
 9034:                     }
 9035:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
 9036:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
 9037:                         $count += $numchg;
 9038:                     }
 9039:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
 9040:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
 9041:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
 9042:                         $codebasecount ++;
 9043:                     }
 9044:                 }
 9045:             }
 9046:             if ($count || $codebasecount) {
 9047:                 my $saveresult;
 9048:                 if ($context eq 'portfolio' || $context eq 'coursedoc') {
 9049:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
 9050:                     if ($url eq $container) {
 9051:                         my ($fname) = ($container =~ m{/([^/]+)$});
 9052:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9053:                                             $count,'<span class="LC_filename">'.
 9054:                                             $fname.'</span>').'</p>';
 9055:                     } else {
 9056:                          $output = '<p class="LC_error">'.
 9057:                                    &mt('Error: update failed for: [_1].',
 9058:                                    '<span class="LC_filename">'.
 9059:                                    $container.'</span>').'</p>';
 9060:                     }
 9061:                 } else {
 9062:                     if (open(my $fh,">$container")) {
 9063:                         print $fh $content;
 9064:                         close($fh);
 9065:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9066:                                   $count,'<span class="LC_filename">'.
 9067:                                   $container.'</span>').'</p>';
 9068:                     } else {
 9069:                          $output = '<p class="LC_error">'.
 9070:                                    &mt('Error: could not update [_1].',
 9071:                                    '<span class="LC_filename">'.
 9072:                                    $container.'</span>').'</p>';
 9073:                     }
 9074:                 }
 9075:             }
 9076:         } else {
 9077:             &logthis('Failed to parse '.$container.
 9078:                      ' to modify references: '.$parse_result);
 9079:         }
 9080:     }
 9081:     return $output;
 9082: }
 9083: 
 9084: sub check_for_existing {
 9085:     my ($path,$fname,$element) = @_;
 9086:     my ($state,$msg);
 9087:     if (-d $path.'/'.$fname) {
 9088:         $state = 'exists';
 9089:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 9090:     } elsif (-e $path.'/'.$fname) {
 9091:         $state = 'exists';
 9092:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 9093:     }
 9094:     if ($state eq 'exists') {
 9095:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 9096:     }
 9097:     return ($state,$msg);
 9098: }
 9099: 
 9100: sub check_for_upload {
 9101:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 9102:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 9103:     my $filesize = length($env{'form.'.$element});
 9104:     if (!$filesize) {
 9105:         my $msg = '<span class="LC_error">'.
 9106:                   &mt('Unable to upload [_1]. (size = [_2] bytes)',
 9107:                       '<span class="LC_filename">'.$fname.'</span>',
 9108:                       $filesize).'<br />'.
 9109:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
 9110:                   '</span>';
 9111:         return ('zero_bytes',$msg);
 9112:     }
 9113:     $filesize =  $filesize/1000; #express in k (1024?)
 9114:     my $getpropath = 1;
 9115:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 9116:                                             $getpropath);
 9117:     my $found_file = 0;
 9118:     my $locked_file = 0;
 9119:     my @lockers;
 9120:     my $navmap;
 9121:     if ($env{'request.course.id'}) {
 9122:         $navmap = Apache::lonnavmaps::navmap->new();
 9123:     }
 9124:     foreach my $line (@dir_list) {
 9125:         my ($file_name,$rest)=split(/\&/,$line,2);
 9126:         if ($file_name eq $fname){
 9127:             $file_name = $path.$file_name;
 9128:             if ($group ne '') {
 9129:                 $file_name = $group.$file_name;
 9130:             }
 9131:             $found_file = 1;
 9132:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
 9133:                 foreach my $lock (@lockers) {
 9134:                     if (ref($lock) eq 'ARRAY') {
 9135:                         my ($symb,$crsid) = @{$lock};
 9136:                         if ($crsid eq $env{'request.course.id'}) {
 9137:                             if (ref($navmap)) {
 9138:                                 my $res = $navmap->getBySymb($symb);
 9139:                                 foreach my $part (@{$res->parts()}) {
 9140:                                     my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
 9141:                                     unless (($slot_status == $res->RESERVED) ||
 9142:                                             ($slot_status == $res->RESERVED_LOCATION)) {
 9143:                                         $locked_file = 1;
 9144:                                     }
 9145:                                 }
 9146:                             } else {
 9147:                                 $locked_file = 1;
 9148:                             }
 9149:                         } else {
 9150:                             $locked_file = 1;
 9151:                         }
 9152:                     }
 9153:                 }
 9154:             } else {
 9155:                 my @info = split(/\&/,$rest);
 9156:                 my $currsize = $info[6]/1000;
 9157:                 if ($currsize < $filesize) {
 9158:                     my $extra = $filesize - $currsize;
 9159:                     if (($current_disk_usage + $extra) > $disk_quota) {
 9160:                         my $msg = '<span class="LC_error">'.
 9161:                                   &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.',
 9162:                                       '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
 9163:                                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9164:                                                $disk_quota,$current_disk_usage);
 9165:                         return ('will_exceed_quota',$msg);
 9166:                     }
 9167:                 }
 9168:             }
 9169:         }
 9170:     }
 9171:     if (($current_disk_usage + $filesize) > $disk_quota){
 9172:         my $msg = '<span class="LC_error">'.
 9173:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 9174:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 9175:         return ('will_exceed_quota',$msg);
 9176:     } elsif ($found_file) {
 9177:         if ($locked_file) {
 9178:             my $msg = '<span class="LC_error">';
 9179:             $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>');
 9180:             $msg .= '</span><br />';
 9181:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 9182:             return ('file_locked',$msg);
 9183:         } else {
 9184:             my $msg = '<span class="LC_error">';
 9185:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 9186:             $msg .= '</span>';
 9187:             return ('existingfile',$msg);
 9188:         }
 9189:     }
 9190: }
 9191: 
 9192: sub check_for_traversal {
 9193:     my ($path,$url,$toplevel) = @_;
 9194:     my @parts=split(/\//,$path);
 9195:     my $cleanpath;
 9196:     my $fullpath = $url;
 9197:     for (my $i=0;$i<@parts;$i++) {
 9198:         next if ($parts[$i] eq '.');
 9199:         if ($parts[$i] eq '..') {
 9200:             $fullpath =~ s{([^/]+/)$}{};
 9201:         } else {
 9202:             $fullpath .= $parts[$i].'/';
 9203:         }
 9204:     }
 9205:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
 9206:         $cleanpath = $1;
 9207:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
 9208:         my $curr_toprel = $1;
 9209:         my @parts = split(/\//,$curr_toprel);
 9210:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
 9211:         my @urlparts = split(/\//,$url_toprel);
 9212:         my $doubledots;
 9213:         my $startdiff = -1;
 9214:         for (my $i=0; $i<@urlparts; $i++) {
 9215:             if ($startdiff == -1) {
 9216:                 unless ($urlparts[$i] eq $parts[$i]) {
 9217:                     $startdiff = $i;
 9218:                     $doubledots .= '../';
 9219:                 }
 9220:             } else {
 9221:                 $doubledots .= '../';
 9222:             }
 9223:         }
 9224:         if ($startdiff > -1) {
 9225:             $cleanpath = $doubledots;
 9226:             for (my $i=$startdiff; $i<@parts; $i++) {
 9227:                 $cleanpath .= $parts[$i].'/';
 9228:             }
 9229:         }
 9230:     }
 9231:     $cleanpath =~ s{(/)$}{};
 9232:     return $cleanpath;
 9233: }
 9234: 
 9235: =pod
 9236: 
 9237: =back
 9238: 
 9239: =head1 CSV Upload/Handling functions
 9240: 
 9241: =over 4
 9242: 
 9243: =item * &upfile_store($r)
 9244: 
 9245: Store uploaded file, $r should be the HTTP Request object,
 9246: needs $env{'form.upfile'}
 9247: returns $datatoken to be put into hidden field
 9248: 
 9249: =cut
 9250: 
 9251: sub upfile_store {
 9252:     my $r=shift;
 9253:     $env{'form.upfile'}=~s/\r/\n/gs;
 9254:     $env{'form.upfile'}=~s/\f/\n/gs;
 9255:     $env{'form.upfile'}=~s/\n+/\n/gs;
 9256:     $env{'form.upfile'}=~s/\n+$//gs;
 9257: 
 9258:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 9259: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 9260:     {
 9261:         my $datafile = $r->dir_config('lonDaemons').
 9262:                            '/tmp/'.$datatoken.'.tmp';
 9263:         if ( open(my $fh,">$datafile") ) {
 9264:             print $fh $env{'form.upfile'};
 9265:             close($fh);
 9266:         }
 9267:     }
 9268:     return $datatoken;
 9269: }
 9270: 
 9271: =pod
 9272: 
 9273: =item * &load_tmp_file($r)
 9274: 
 9275: Load uploaded file from tmp, $r should be the HTTP Request object,
 9276: needs $env{'form.datatoken'},
 9277: sets $env{'form.upfile'} to the contents of the file
 9278: 
 9279: =cut
 9280: 
 9281: sub load_tmp_file {
 9282:     my $r=shift;
 9283:     my @studentdata=();
 9284:     {
 9285:         my $studentfile = $r->dir_config('lonDaemons').
 9286:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 9287:         if ( open(my $fh,"<$studentfile") ) {
 9288:             @studentdata=<$fh>;
 9289:             close($fh);
 9290:         }
 9291:     }
 9292:     $env{'form.upfile'}=join('',@studentdata);
 9293: }
 9294: 
 9295: =pod
 9296: 
 9297: =item * &upfile_record_sep()
 9298: 
 9299: Separate uploaded file into records
 9300: returns array of records,
 9301: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 9302: 
 9303: =cut
 9304: 
 9305: sub upfile_record_sep {
 9306:     if ($env{'form.upfiletype'} eq 'xml') {
 9307:     } else {
 9308: 	my @records;
 9309: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 9310: 	    if ($line=~/^\s*$/) { next; }
 9311: 	    push(@records,$line);
 9312: 	}
 9313: 	return @records;
 9314:     }
 9315: }
 9316: 
 9317: =pod
 9318: 
 9319: =item * &record_sep($record)
 9320: 
 9321: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 9322: 
 9323: =cut
 9324: 
 9325: sub takeleft {
 9326:     my $index=shift;
 9327:     return substr('0000'.$index,-4,4);
 9328: }
 9329: 
 9330: sub record_sep {
 9331:     my $record=shift;
 9332:     my %components=();
 9333:     if ($env{'form.upfiletype'} eq 'xml') {
 9334:     } elsif ($env{'form.upfiletype'} eq 'space') {
 9335:         my $i=0;
 9336:         foreach my $field (split(/\s+/,$record)) {
 9337:             $field=~s/^(\"|\')//;
 9338:             $field=~s/(\"|\')$//;
 9339:             $components{&takeleft($i)}=$field;
 9340:             $i++;
 9341:         }
 9342:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 9343:         my $i=0;
 9344:         foreach my $field (split(/\t/,$record)) {
 9345:             $field=~s/^(\"|\')//;
 9346:             $field=~s/(\"|\')$//;
 9347:             $components{&takeleft($i)}=$field;
 9348:             $i++;
 9349:         }
 9350:     } else {
 9351:         my $separator=',';
 9352:         if ($env{'form.upfiletype'} eq 'semisv') {
 9353:             $separator=';';
 9354:         }
 9355:         my $i=0;
 9356: # the character we are looking for to indicate the end of a quote or a record 
 9357:         my $looking_for=$separator;
 9358: # do not add the characters to the fields
 9359:         my $ignore=0;
 9360: # we just encountered a separator (or the beginning of the record)
 9361:         my $just_found_separator=1;
 9362: # store the field we are working on here
 9363:         my $field='';
 9364: # work our way through all characters in record
 9365:         foreach my $character ($record=~/(.)/g) {
 9366:             if ($character eq $looking_for) {
 9367:                if ($character ne $separator) {
 9368: # Found the end of a quote, again looking for separator
 9369:                   $looking_for=$separator;
 9370:                   $ignore=1;
 9371:                } else {
 9372: # Found a separator, store away what we got
 9373:                   $components{&takeleft($i)}=$field;
 9374: 	          $i++;
 9375:                   $just_found_separator=1;
 9376:                   $ignore=0;
 9377:                   $field='';
 9378:                }
 9379:                next;
 9380:             }
 9381: # single or double quotation marks after a separator indicate beginning of a quote
 9382: # we are now looking for the end of the quote and need to ignore separators
 9383:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 9384:                $looking_for=$character;
 9385:                next;
 9386:             }
 9387: # ignore would be true after we reached the end of a quote
 9388:             if ($ignore) { next; }
 9389:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 9390:             $field.=$character;
 9391:             $just_found_separator=0; 
 9392:         }
 9393: # catch the very last entry, since we never encountered the separator
 9394:         $components{&takeleft($i)}=$field;
 9395:     }
 9396:     return %components;
 9397: }
 9398: 
 9399: ######################################################
 9400: ######################################################
 9401: 
 9402: =pod
 9403: 
 9404: =item * &upfile_select_html()
 9405: 
 9406: Return HTML code to select a file from the users machine and specify 
 9407: the file type.
 9408: 
 9409: =cut
 9410: 
 9411: ######################################################
 9412: ######################################################
 9413: sub upfile_select_html {
 9414:     my %Types = (
 9415:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 9416:                  semisv => &mt('Semicolon separated values'),
 9417:                  space => &mt('Space separated'),
 9418:                  tab   => &mt('Tabulator separated'),
 9419: #                 xml   => &mt('HTML/XML'),
 9420:                  );
 9421:     my $Str = '<input type="file" name="upfile" size="50" />'.
 9422:         '<br />'.&mt('Type').': <select name="upfiletype">';
 9423:     foreach my $type (sort(keys(%Types))) {
 9424:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 9425:     }
 9426:     $Str .= "</select>\n";
 9427:     return $Str;
 9428: }
 9429: 
 9430: sub get_samples {
 9431:     my ($records,$toget) = @_;
 9432:     my @samples=({});
 9433:     my $got=0;
 9434:     foreach my $rec (@$records) {
 9435: 	my %temp = &record_sep($rec);
 9436: 	if (! grep(/\S/, values(%temp))) { next; }
 9437: 	if (%temp) {
 9438: 	    $samples[$got]=\%temp;
 9439: 	    $got++;
 9440: 	    if ($got == $toget) { last; }
 9441: 	}
 9442:     }
 9443:     return \@samples;
 9444: }
 9445: 
 9446: ######################################################
 9447: ######################################################
 9448: 
 9449: =pod
 9450: 
 9451: =item * &csv_print_samples($r,$records)
 9452: 
 9453: Prints a table of sample values from each column uploaded $r is an
 9454: Apache Request ref, $records is an arrayref from
 9455: &Apache::loncommon::upfile_record_sep
 9456: 
 9457: =cut
 9458: 
 9459: ######################################################
 9460: ######################################################
 9461: sub csv_print_samples {
 9462:     my ($r,$records) = @_;
 9463:     my $samples = &get_samples($records,5);
 9464: 
 9465:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 9466:               &start_data_table_header_row());
 9467:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 9468:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 9469:     $r->print(&end_data_table_header_row());
 9470:     foreach my $hash (@$samples) {
 9471: 	$r->print(&start_data_table_row());
 9472: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9473: 	    $r->print('<td>');
 9474: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 9475: 	    $r->print('</td>');
 9476: 	}
 9477: 	$r->print(&end_data_table_row());
 9478:     }
 9479:     $r->print(&end_data_table().'<br />'."\n");
 9480: }
 9481: 
 9482: ######################################################
 9483: ######################################################
 9484: 
 9485: =pod
 9486: 
 9487: =item * &csv_print_select_table($r,$records,$d)
 9488: 
 9489: Prints a table to create associations between values and table columns.
 9490: 
 9491: $r is an Apache Request ref,
 9492: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9493: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 9494: 
 9495: =cut
 9496: 
 9497: ######################################################
 9498: ######################################################
 9499: sub csv_print_select_table {
 9500:     my ($r,$records,$d) = @_;
 9501:     my $i=0;
 9502:     my $samples = &get_samples($records,1);
 9503:     $r->print(&mt('Associate columns with student attributes.')."\n".
 9504: 	      &start_data_table().&start_data_table_header_row().
 9505:               '<th>'.&mt('Attribute').'</th>'.
 9506:               '<th>'.&mt('Column').'</th>'.
 9507:               &end_data_table_header_row()."\n");
 9508:     foreach my $array_ref (@$d) {
 9509: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 9510: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 9511: 
 9512: 	$r->print('<td><select name="f'.$i.'"'.
 9513: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9514: 	$r->print('<option value="none"></option>');
 9515: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9516: 	    $r->print('<option value="'.$sample.'"'.
 9517:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 9518:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 9519: 	}
 9520: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 9521: 	$i++;
 9522:     }
 9523:     $r->print(&end_data_table());
 9524:     $i--;
 9525:     return $i;
 9526: }
 9527: 
 9528: ######################################################
 9529: ######################################################
 9530: 
 9531: =pod
 9532: 
 9533: =item * &csv_samples_select_table($r,$records,$d)
 9534: 
 9535: Prints a table of sample values from the upload and can make associate samples to internal names.
 9536: 
 9537: $r is an Apache Request ref,
 9538: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9539: $d is an array of 2 element arrays (internal name, displayed name)
 9540: 
 9541: =cut
 9542: 
 9543: ######################################################
 9544: ######################################################
 9545: sub csv_samples_select_table {
 9546:     my ($r,$records,$d) = @_;
 9547:     my $i=0;
 9548:     #
 9549:     my $max_samples = 5;
 9550:     my $samples = &get_samples($records,$max_samples);
 9551:     $r->print(&start_data_table().
 9552:               &start_data_table_header_row().'<th>'.
 9553:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 9554:               &end_data_table_header_row());
 9555: 
 9556:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 9557: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 9558: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9559: 	foreach my $option (@$d) {
 9560: 	    my ($value,$display,$defaultcol)=@{ $option };
 9561: 	    $r->print('<option value="'.$value.'"'.
 9562:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 9563:                       $display.'</option>');
 9564: 	}
 9565: 	$r->print('</select></td><td>');
 9566: 	foreach my $line (0..($max_samples-1)) {
 9567: 	    if (defined($samples->[$line]{$key})) { 
 9568: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 9569: 	    }
 9570: 	}
 9571: 	$r->print('</td>'.&end_data_table_row());
 9572: 	$i++;
 9573:     }
 9574:     $r->print(&end_data_table());
 9575:     $i--;
 9576:     return($i);
 9577: }
 9578: 
 9579: ######################################################
 9580: ######################################################
 9581: 
 9582: =pod
 9583: 
 9584: =item * &clean_excel_name($name)
 9585: 
 9586: Returns a replacement for $name which does not contain any illegal characters.
 9587: 
 9588: =cut
 9589: 
 9590: ######################################################
 9591: ######################################################
 9592: sub clean_excel_name {
 9593:     my ($name) = @_;
 9594:     $name =~ s/[:\*\?\/\\]//g;
 9595:     if (length($name) > 31) {
 9596:         $name = substr($name,0,31);
 9597:     }
 9598:     return $name;
 9599: }
 9600: 
 9601: =pod
 9602: 
 9603: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 9604: 
 9605: Returns either 1 or undef
 9606: 
 9607: 1 if the part is to be hidden, undef if it is to be shown
 9608: 
 9609: Arguments are:
 9610: 
 9611: $id the id of the part to be checked
 9612: $symb, optional the symb of the resource to check
 9613: $udom, optional the domain of the user to check for
 9614: $uname, optional the username of the user to check for
 9615: 
 9616: =cut
 9617: 
 9618: sub check_if_partid_hidden {
 9619:     my ($id,$symb,$udom,$uname) = @_;
 9620:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 9621: 					 $symb,$udom,$uname);
 9622:     my $truth=1;
 9623:     #if the string starts with !, then the list is the list to show not hide
 9624:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 9625:     my @hiddenlist=split(/,/,$hiddenparts);
 9626:     foreach my $checkid (@hiddenlist) {
 9627: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 9628:     }
 9629:     return !$truth;
 9630: }
 9631: 
 9632: 
 9633: ############################################################
 9634: ############################################################
 9635: 
 9636: =pod
 9637: 
 9638: =back 
 9639: 
 9640: =head1 cgi-bin script and graphing routines
 9641: 
 9642: =over 4
 9643: 
 9644: =item * &get_cgi_id()
 9645: 
 9646: Inputs: none
 9647: 
 9648: Returns an id which can be used to pass environment variables
 9649: to various cgi-bin scripts.  These environment variables will
 9650: be removed from the users environment after a given time by
 9651: the routine &Apache::lonnet::transfer_profile_to_env.
 9652: 
 9653: =cut
 9654: 
 9655: ############################################################
 9656: ############################################################
 9657: my $uniq=0;
 9658: sub get_cgi_id {
 9659:     $uniq=($uniq+1)%100000;
 9660:     return (time.'_'.$$.'_'.$uniq);
 9661: }
 9662: 
 9663: ############################################################
 9664: ############################################################
 9665: 
 9666: =pod
 9667: 
 9668: =item * &DrawBarGraph()
 9669: 
 9670: Facilitates the plotting of data in a (stacked) bar graph.
 9671: Puts plot definition data into the users environment in order for 
 9672: graph.png to plot it.  Returns an <img> tag for the plot.
 9673: The bars on the plot are labeled '1','2',...,'n'.
 9674: 
 9675: Inputs:
 9676: 
 9677: =over 4
 9678: 
 9679: =item $Title: string, the title of the plot
 9680: 
 9681: =item $xlabel: string, text describing the X-axis of the plot
 9682: 
 9683: =item $ylabel: string, text describing the Y-axis of the plot
 9684: 
 9685: =item $Max: scalar, the maximum Y value to use in the plot
 9686: If $Max is < any data point, the graph will not be rendered.
 9687: 
 9688: =item $colors: array ref holding the colors to be used for the data sets when
 9689: they are plotted.  If undefined, default values will be used.
 9690: 
 9691: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 9692: 
 9693: =item @Values: An array of array references.  Each array reference holds data
 9694: to be plotted in a stacked bar chart.
 9695: 
 9696: =item If the final element of @Values is a hash reference the key/value
 9697: pairs will be added to the graph definition.
 9698: 
 9699: =back
 9700: 
 9701: Returns:
 9702: 
 9703: An <img> tag which references graph.png and the appropriate identifying
 9704: information for the plot.
 9705: 
 9706: =cut
 9707: 
 9708: ############################################################
 9709: ############################################################
 9710: sub DrawBarGraph {
 9711:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9712:     #
 9713:     if (! defined($colors)) {
 9714:         $colors = ['#33ff00', 
 9715:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9716:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9717:                   ]; 
 9718:     }
 9719:     my $extra_settings = {};
 9720:     if (ref($Values[-1]) eq 'HASH') {
 9721:         $extra_settings = pop(@Values);
 9722:     }
 9723:     #
 9724:     my $identifier = &get_cgi_id();
 9725:     my $id = 'cgi.'.$identifier;        
 9726:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9727:         return '';
 9728:     }
 9729:     #
 9730:     my @Labels;
 9731:     if (defined($labels)) {
 9732:         @Labels = @$labels;
 9733:     } else {
 9734:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9735:             push (@Labels,$i+1);
 9736:         }
 9737:     }
 9738:     #
 9739:     my $NumBars = scalar(@{$Values[0]});
 9740:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9741:     my %ValuesHash;
 9742:     my $NumSets=1;
 9743:     foreach my $array (@Values) {
 9744:         next if (! ref($array));
 9745:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9746:             join(',',@$array);
 9747:     }
 9748:     #
 9749:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9750:     if ($NumBars < 3) {
 9751:         $width = 120+$NumBars*32;
 9752:         $xskip = 1;
 9753:         $bar_width = 30;
 9754:     } elsif ($NumBars < 5) {
 9755:         $width = 120+$NumBars*20;
 9756:         $xskip = 1;
 9757:         $bar_width = 20;
 9758:     } elsif ($NumBars < 10) {
 9759:         $width = 120+$NumBars*15;
 9760:         $xskip = 1;
 9761:         $bar_width = 15;
 9762:     } elsif ($NumBars <= 25) {
 9763:         $width = 120+$NumBars*11;
 9764:         $xskip = 5;
 9765:         $bar_width = 8;
 9766:     } elsif ($NumBars <= 50) {
 9767:         $width = 120+$NumBars*8;
 9768:         $xskip = 5;
 9769:         $bar_width = 4;
 9770:     } else {
 9771:         $width = 120+$NumBars*8;
 9772:         $xskip = 5;
 9773:         $bar_width = 4;
 9774:     }
 9775:     #
 9776:     $Max = 1 if ($Max < 1);
 9777:     if ( int($Max) < $Max ) {
 9778:         $Max++;
 9779:         $Max = int($Max);
 9780:     }
 9781:     $Title  = '' if (! defined($Title));
 9782:     $xlabel = '' if (! defined($xlabel));
 9783:     $ylabel = '' if (! defined($ylabel));
 9784:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9785:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9786:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9787:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9788:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9789:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9790:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9791:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9792:     $ValuesHash{$id.'.height'}   = $height;
 9793:     $ValuesHash{$id.'.width'}    = $width;
 9794:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9795:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 9796:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 9797:     #
 9798:     # Deal with other parameters
 9799:     while (my ($key,$value) = each(%$extra_settings)) {
 9800:         $ValuesHash{$id.'.'.$key} = $value;
 9801:     }
 9802:     #
 9803:     &Apache::lonnet::appenv(\%ValuesHash);
 9804:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9805: }
 9806: 
 9807: ############################################################
 9808: ############################################################
 9809: 
 9810: =pod
 9811: 
 9812: =item * &DrawXYGraph()
 9813: 
 9814: Facilitates the plotting of data in an XY graph.
 9815: Puts plot definition data into the users environment in order for 
 9816: graph.png to plot it.  Returns an <img> tag for the plot.
 9817: 
 9818: Inputs:
 9819: 
 9820: =over 4
 9821: 
 9822: =item $Title: string, the title of the plot
 9823: 
 9824: =item $xlabel: string, text describing the X-axis of the plot
 9825: 
 9826: =item $ylabel: string, text describing the Y-axis of the plot
 9827: 
 9828: =item $Max: scalar, the maximum Y value to use in the plot
 9829: If $Max is < any data point, the graph will not be rendered.
 9830: 
 9831: =item $colors: Array ref containing the hex color codes for the data to be 
 9832: plotted in.  If undefined, default values will be used.
 9833: 
 9834: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9835: 
 9836: =item $Ydata: Array ref containing Array refs.  
 9837: Each of the contained arrays will be plotted as a separate curve.
 9838: 
 9839: =item %Values: hash indicating or overriding any default values which are 
 9840: passed to graph.png.  
 9841: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9842: 
 9843: =back
 9844: 
 9845: Returns:
 9846: 
 9847: An <img> tag which references graph.png and the appropriate identifying
 9848: information for the plot.
 9849: 
 9850: =cut
 9851: 
 9852: ############################################################
 9853: ############################################################
 9854: sub DrawXYGraph {
 9855:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9856:     #
 9857:     # Create the identifier for the graph
 9858:     my $identifier = &get_cgi_id();
 9859:     my $id = 'cgi.'.$identifier;
 9860:     #
 9861:     $Title  = '' if (! defined($Title));
 9862:     $xlabel = '' if (! defined($xlabel));
 9863:     $ylabel = '' if (! defined($ylabel));
 9864:     my %ValuesHash = 
 9865:         (
 9866:          $id.'.title'  => &escape($Title),
 9867:          $id.'.xlabel' => &escape($xlabel),
 9868:          $id.'.ylabel' => &escape($ylabel),
 9869:          $id.'.y_max_value'=> $Max,
 9870:          $id.'.labels'     => join(',',@$Xlabels),
 9871:          $id.'.PlotType'   => 'XY',
 9872:          );
 9873:     #
 9874:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9875:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9876:     }
 9877:     #
 9878:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9879:         return '';
 9880:     }
 9881:     my $NumSets=1;
 9882:     foreach my $array (@{$Ydata}){
 9883:         next if (! ref($array));
 9884:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9885:     }
 9886:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9887:     #
 9888:     # Deal with other parameters
 9889:     while (my ($key,$value) = each(%Values)) {
 9890:         $ValuesHash{$id.'.'.$key} = $value;
 9891:     }
 9892:     #
 9893:     &Apache::lonnet::appenv(\%ValuesHash);
 9894:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9895: }
 9896: 
 9897: ############################################################
 9898: ############################################################
 9899: 
 9900: =pod
 9901: 
 9902: =item * &DrawXYYGraph()
 9903: 
 9904: Facilitates the plotting of data in an XY graph with two Y axes.
 9905: Puts plot definition data into the users environment in order for 
 9906: graph.png to plot it.  Returns an <img> tag for the plot.
 9907: 
 9908: Inputs:
 9909: 
 9910: =over 4
 9911: 
 9912: =item $Title: string, the title of the plot
 9913: 
 9914: =item $xlabel: string, text describing the X-axis of the plot
 9915: 
 9916: =item $ylabel: string, text describing the Y-axis of the plot
 9917: 
 9918: =item $colors: Array ref containing the hex color codes for the data to be 
 9919: plotted in.  If undefined, default values will be used.
 9920: 
 9921: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9922: 
 9923: =item $Ydata1: The first data set
 9924: 
 9925: =item $Min1: The minimum value of the left Y-axis
 9926: 
 9927: =item $Max1: The maximum value of the left Y-axis
 9928: 
 9929: =item $Ydata2: The second data set
 9930: 
 9931: =item $Min2: The minimum value of the right Y-axis
 9932: 
 9933: =item $Max2: The maximum value of the left Y-axis
 9934: 
 9935: =item %Values: hash indicating or overriding any default values which are 
 9936: passed to graph.png.  
 9937: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9938: 
 9939: =back
 9940: 
 9941: Returns:
 9942: 
 9943: An <img> tag which references graph.png and the appropriate identifying
 9944: information for the plot.
 9945: 
 9946: =cut
 9947: 
 9948: ############################################################
 9949: ############################################################
 9950: sub DrawXYYGraph {
 9951:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9952:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9953:     #
 9954:     # Create the identifier for the graph
 9955:     my $identifier = &get_cgi_id();
 9956:     my $id = 'cgi.'.$identifier;
 9957:     #
 9958:     $Title  = '' if (! defined($Title));
 9959:     $xlabel = '' if (! defined($xlabel));
 9960:     $ylabel = '' if (! defined($ylabel));
 9961:     my %ValuesHash = 
 9962:         (
 9963:          $id.'.title'  => &escape($Title),
 9964:          $id.'.xlabel' => &escape($xlabel),
 9965:          $id.'.ylabel' => &escape($ylabel),
 9966:          $id.'.labels' => join(',',@$Xlabels),
 9967:          $id.'.PlotType' => 'XY',
 9968:          $id.'.NumSets' => 2,
 9969:          $id.'.two_axes' => 1,
 9970:          $id.'.y1_max_value' => $Max1,
 9971:          $id.'.y1_min_value' => $Min1,
 9972:          $id.'.y2_max_value' => $Max2,
 9973:          $id.'.y2_min_value' => $Min2,
 9974:          );
 9975:     #
 9976:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9977:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9978:     }
 9979:     #
 9980:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9981:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9982:         return '';
 9983:     }
 9984:     my $NumSets=1;
 9985:     foreach my $array ($Ydata1,$Ydata2){
 9986:         next if (! ref($array));
 9987:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9988:     }
 9989:     #
 9990:     # Deal with other parameters
 9991:     while (my ($key,$value) = each(%Values)) {
 9992:         $ValuesHash{$id.'.'.$key} = $value;
 9993:     }
 9994:     #
 9995:     &Apache::lonnet::appenv(\%ValuesHash);
 9996:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9997: }
 9998: 
 9999: ############################################################
10000: ############################################################
10001: 
10002: =pod
10003: 
10004: =back 
10005: 
10006: =head1 Statistics helper routines?  
10007: 
10008: Bad place for them but what the hell.
10009: 
10010: =over 4
10011: 
10012: =item * &chartlink()
10013: 
10014: Returns a link to the chart for a specific student.  
10015: 
10016: Inputs:
10017: 
10018: =over 4
10019: 
10020: =item $linktext: The text of the link
10021: 
10022: =item $sname: The students username
10023: 
10024: =item $sdomain: The students domain
10025: 
10026: =back
10027: 
10028: =back
10029: 
10030: =cut
10031: 
10032: ############################################################
10033: ############################################################
10034: sub chartlink {
10035:     my ($linktext, $sname, $sdomain) = @_;
10036:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
10037:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
10038:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
10039:        '">'.$linktext.'</a>';
10040: }
10041: 
10042: #######################################################
10043: #######################################################
10044: 
10045: =pod
10046: 
10047: =head1 Course Environment Routines
10048: 
10049: =over 4
10050: 
10051: =item * &restore_course_settings()
10052: 
10053: =item * &store_course_settings()
10054: 
10055: Restores/Store indicated form parameters from the course environment.
10056: Will not overwrite existing values of the form parameters.
10057: 
10058: Inputs: 
10059: a scalar describing the data (e.g. 'chart', 'problem_analysis')
10060: 
10061: a hash ref describing the data to be stored.  For example:
10062:    
10063: %Save_Parameters = ('Status' => 'scalar',
10064:     'chartoutputmode' => 'scalar',
10065:     'chartoutputdata' => 'scalar',
10066:     'Section' => 'array',
10067:     'Group' => 'array',
10068:     'StudentData' => 'array',
10069:     'Maps' => 'array');
10070: 
10071: Returns: both routines return nothing
10072: 
10073: =back
10074: 
10075: =cut
10076: 
10077: #######################################################
10078: #######################################################
10079: sub store_course_settings {
10080:     return &store_settings($env{'request.course.id'},@_);
10081: }
10082: 
10083: sub store_settings {
10084:     # save to the environment
10085:     # appenv the same items, just to be safe
10086:     my $udom  = $env{'user.domain'};
10087:     my $uname = $env{'user.name'};
10088:     my ($context,$prefix,$Settings) = @_;
10089:     my %SaveHash;
10090:     my %AppHash;
10091:     while (my ($setting,$type) = each(%$Settings)) {
10092:         my $basename = join('.','internal',$context,$prefix,$setting);
10093:         my $envname = 'environment.'.$basename;
10094:         if (exists($env{'form.'.$setting})) {
10095:             # Save this value away
10096:             if ($type eq 'scalar' &&
10097:                 (! exists($env{$envname}) || 
10098:                  $env{$envname} ne $env{'form.'.$setting})) {
10099:                 $SaveHash{$basename} = $env{'form.'.$setting};
10100:                 $AppHash{$envname}   = $env{'form.'.$setting};
10101:             } elsif ($type eq 'array') {
10102:                 my $stored_form;
10103:                 if (ref($env{'form.'.$setting})) {
10104:                     $stored_form = join(',',
10105:                                         map {
10106:                                             &escape($_);
10107:                                         } sort(@{$env{'form.'.$setting}}));
10108:                 } else {
10109:                     $stored_form = 
10110:                         &escape($env{'form.'.$setting});
10111:                 }
10112:                 # Determine if the array contents are the same.
10113:                 if ($stored_form ne $env{$envname}) {
10114:                     $SaveHash{$basename} = $stored_form;
10115:                     $AppHash{$envname}   = $stored_form;
10116:                 }
10117:             }
10118:         }
10119:     }
10120:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
10121:                                           $udom,$uname);
10122:     if ($put_result !~ /^(ok|delayed)/) {
10123:         &Apache::lonnet::logthis('unable to save form parameters, '.
10124:                                  'got error:'.$put_result);
10125:     }
10126:     # Make sure these settings stick around in this session, too
10127:     &Apache::lonnet::appenv(\%AppHash);
10128:     return;
10129: }
10130: 
10131: sub restore_course_settings {
10132:     return &restore_settings($env{'request.course.id'},@_);
10133: }
10134: 
10135: sub restore_settings {
10136:     my ($context,$prefix,$Settings) = @_;
10137:     while (my ($setting,$type) = each(%$Settings)) {
10138:         next if (exists($env{'form.'.$setting}));
10139:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
10140:             '.'.$setting;
10141:         if (exists($env{$envname})) {
10142:             if ($type eq 'scalar') {
10143:                 $env{'form.'.$setting} = $env{$envname};
10144:             } elsif ($type eq 'array') {
10145:                 $env{'form.'.$setting} = [ 
10146:                                            map { 
10147:                                                &unescape($_); 
10148:                                            } split(',',$env{$envname})
10149:                                            ];
10150:             }
10151:         }
10152:     }
10153: }
10154: 
10155: #######################################################
10156: #######################################################
10157: 
10158: =pod
10159: 
10160: =head1 Domain E-mail Routines  
10161: 
10162: =over 4
10163: 
10164: =item * &build_recipient_list()
10165: 
10166: Build recipient lists for five types of e-mail:
10167: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
10168: (d) Help requests, (e) Course requests needing approval,  generated by
10169: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
10170: loncoursequeueadmin.pm respectively.
10171: 
10172: Inputs:
10173: defmail (scalar - email address of default recipient), 
10174: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
10175: defdom (domain for which to retrieve configuration settings),
10176: origmail (scalar - email address of recipient from loncapa.conf, 
10177: i.e., predates configuration by DC via domainprefs.pm 
10178: 
10179: Returns: comma separated list of addresses to which to send e-mail.
10180: 
10181: =back
10182: 
10183: =cut
10184: 
10185: ############################################################
10186: ############################################################
10187: sub build_recipient_list {
10188:     my ($defmail,$mailing,$defdom,$origmail) = @_;
10189:     my @recipients;
10190:     my $otheremails;
10191:     my %domconfig =
10192:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
10193:     if (ref($domconfig{'contacts'}) eq 'HASH') {
10194:         if (exists($domconfig{'contacts'}{$mailing})) {
10195:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
10196:                 my @contacts = ('adminemail','supportemail');
10197:                 foreach my $item (@contacts) {
10198:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
10199:                         my $addr = $domconfig{'contacts'}{$item}; 
10200:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
10201:                             push(@recipients,$addr);
10202:                         }
10203:                     }
10204:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
10205:                 }
10206:             }
10207:         } elsif ($origmail ne '') {
10208:             push(@recipients,$origmail);
10209:         }
10210:     } elsif ($origmail ne '') {
10211:         push(@recipients,$origmail);
10212:     }
10213:     if (defined($defmail)) {
10214:         if ($defmail ne '') {
10215:             push(@recipients,$defmail);
10216:         }
10217:     }
10218:     if ($otheremails) {
10219:         my @others;
10220:         if ($otheremails =~ /,/) {
10221:             @others = split(/,/,$otheremails);
10222:         } else {
10223:             push(@others,$otheremails);
10224:         }
10225:         foreach my $addr (@others) {
10226:             if (!grep(/^\Q$addr\E$/,@recipients)) {
10227:                 push(@recipients,$addr);
10228:             }
10229:         }
10230:     }
10231:     my $recipientlist = join(',',@recipients); 
10232:     return $recipientlist;
10233: }
10234: 
10235: ############################################################
10236: ############################################################
10237: 
10238: =pod
10239: 
10240: =head1 Course Catalog Routines
10241: 
10242: =over 4
10243: 
10244: =item * &gather_categories()
10245: 
10246: Converts category definitions - keys of categories hash stored in  
10247: coursecategories in configuration.db on the primary library server in a 
10248: domain - to an array.  Also generates javascript and idx hash used to 
10249: generate Domain Coordinator interface for editing Course Categories.
10250: 
10251: Inputs:
10252: 
10253: categories (reference to hash of category definitions).
10254: 
10255: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10256:       categories and subcategories).
10257: 
10258: idx (reference to hash of counters used in Domain Coordinator interface for 
10259:       editing Course Categories).
10260: 
10261: jsarray (reference to array of categories used to create Javascript arrays for
10262:          Domain Coordinator interface for editing Course Categories).
10263: 
10264: Returns: nothing
10265: 
10266: Side effects: populates cats, idx and jsarray. 
10267: 
10268: =cut
10269: 
10270: sub gather_categories {
10271:     my ($categories,$cats,$idx,$jsarray) = @_;
10272:     my %counters;
10273:     my $num = 0;
10274:     foreach my $item (keys(%{$categories})) {
10275:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10276:         if ($container eq '' && $depth == 0) {
10277:             $cats->[$depth][$categories->{$item}] = $cat;
10278:         } else {
10279:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
10280:         }
10281:         my ($escitem,$tail) = split(/:/,$item,2);
10282:         if ($counters{$tail} eq '') {
10283:             $counters{$tail} = $num;
10284:             $num ++;
10285:         }
10286:         if (ref($idx) eq 'HASH') {
10287:             $idx->{$item} = $counters{$tail};
10288:         }
10289:         if (ref($jsarray) eq 'ARRAY') {
10290:             push(@{$jsarray->[$counters{$tail}]},$item);
10291:         }
10292:     }
10293:     return;
10294: }
10295: 
10296: =pod
10297: 
10298: =item * &extract_categories()
10299: 
10300: Used to generate breadcrumb trails for course categories.
10301: 
10302: Inputs:
10303: 
10304: categories (reference to hash of category definitions).
10305: 
10306: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10307:       categories and subcategories).
10308: 
10309: trails (reference to array of breacrumb trails for each category).
10310: 
10311: allitems (reference to hash - key is category key 
10312:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10313: 
10314: idx (reference to hash of counters used in Domain Coordinator interface for
10315:       editing Course Categories).
10316: 
10317: jsarray (reference to array of categories used to create Javascript arrays for
10318:          Domain Coordinator interface for editing Course Categories).
10319: 
10320: subcats (reference to hash of arrays containing all subcategories within each 
10321:          category, -recursive)
10322: 
10323: Returns: nothing
10324: 
10325: Side effects: populates trails and allitems hash references.
10326: 
10327: =cut
10328: 
10329: sub extract_categories {
10330:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
10331:     if (ref($categories) eq 'HASH') {
10332:         &gather_categories($categories,$cats,$idx,$jsarray);
10333:         if (ref($cats->[0]) eq 'ARRAY') {
10334:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
10335:                 my $name = $cats->[0][$i];
10336:                 my $item = &escape($name).'::0';
10337:                 my $trailstr;
10338:                 if ($name eq 'instcode') {
10339:                     $trailstr = &mt('Official courses (with institutional codes)');
10340:                 } elsif ($name eq 'communities') {
10341:                     $trailstr = &mt('Communities');
10342:                 } else {
10343:                     $trailstr = $name;
10344:                 }
10345:                 if ($allitems->{$item} eq '') {
10346:                     push(@{$trails},$trailstr);
10347:                     $allitems->{$item} = scalar(@{$trails})-1;
10348:                 }
10349:                 my @parents = ($name);
10350:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
10351:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
10352:                         my $category = $cats->[1]{$name}[$j];
10353:                         if (ref($subcats) eq 'HASH') {
10354:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
10355:                         }
10356:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
10357:                     }
10358:                 } else {
10359:                     if (ref($subcats) eq 'HASH') {
10360:                         $subcats->{$item} = [];
10361:                     }
10362:                 }
10363:             }
10364:         }
10365:     }
10366:     return;
10367: }
10368: 
10369: =pod
10370: 
10371: =item *&recurse_categories()
10372: 
10373: Recursively used to generate breadcrumb trails for course categories.
10374: 
10375: Inputs:
10376: 
10377: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10378:       categories and subcategories).
10379: 
10380: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
10381: 
10382: category (current course category, for which breadcrumb trail is being generated).
10383: 
10384: trails (reference to array of breadcrumb trails for each category).
10385: 
10386: allitems (reference to hash - key is category key
10387:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10388: 
10389: parents (array containing containers directories for current category, 
10390:          back to top level). 
10391: 
10392: Returns: nothing
10393: 
10394: Side effects: populates trails and allitems hash references
10395: 
10396: =cut
10397: 
10398: sub recurse_categories {
10399:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
10400:     my $shallower = $depth - 1;
10401:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
10402:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
10403:             my $name = $cats->[$depth]{$category}[$k];
10404:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10405:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
10406:             if ($allitems->{$item} eq '') {
10407:                 push(@{$trails},$trailstr);
10408:                 $allitems->{$item} = scalar(@{$trails})-1;
10409:             }
10410:             my $deeper = $depth+1;
10411:             push(@{$parents},$category);
10412:             if (ref($subcats) eq 'HASH') {
10413:                 my $subcat = &escape($name).':'.$category.':'.$depth;
10414:                 for (my $j=@{$parents}; $j>=0; $j--) {
10415:                     my $higher;
10416:                     if ($j > 0) {
10417:                         $higher = &escape($parents->[$j]).':'.
10418:                                   &escape($parents->[$j-1]).':'.$j;
10419:                     } else {
10420:                         $higher = &escape($parents->[$j]).'::'.$j;
10421:                     }
10422:                     push(@{$subcats->{$higher}},$subcat);
10423:                 }
10424:             }
10425:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
10426:                                 $subcats);
10427:             pop(@{$parents});
10428:         }
10429:     } else {
10430:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10431:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
10432:         if ($allitems->{$item} eq '') {
10433:             push(@{$trails},$trailstr);
10434:             $allitems->{$item} = scalar(@{$trails})-1;
10435:         }
10436:     }
10437:     return;
10438: }
10439: 
10440: =pod
10441: 
10442: =item *&assign_categories_table()
10443: 
10444: Create a datatable for display of hierarchical categories in a domain,
10445: with checkboxes to allow a course to be categorized. 
10446: 
10447: Inputs:
10448: 
10449: cathash - reference to hash of categories defined for the domain (from
10450:           configuration.db)
10451: 
10452: currcat - scalar with an & separated list of categories assigned to a course. 
10453: 
10454: type    - scalar contains course type (Course or Community).
10455: 
10456: Returns: $output (markup to be displayed) 
10457: 
10458: =cut
10459: 
10460: sub assign_categories_table {
10461:     my ($cathash,$currcat,$type) = @_;
10462:     my $output;
10463:     if (ref($cathash) eq 'HASH') {
10464:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
10465:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
10466:         $maxdepth = scalar(@cats);
10467:         if (@cats > 0) {
10468:             my $itemcount = 0;
10469:             if (ref($cats[0]) eq 'ARRAY') {
10470:                 my @currcategories;
10471:                 if ($currcat ne '') {
10472:                     @currcategories = split('&',$currcat);
10473:                 }
10474:                 my $table;
10475:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
10476:                     my $parent = $cats[0][$i];
10477:                     next if ($parent eq 'instcode');
10478:                     if ($type eq 'Community') {
10479:                         next unless ($parent eq 'communities');
10480:                     } else {
10481:                         next if ($parent eq 'communities');
10482:                     }
10483:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10484:                     my $item = &escape($parent).'::0';
10485:                     my $checked = '';
10486:                     if (@currcategories > 0) {
10487:                         if (grep(/^\Q$item\E$/,@currcategories)) {
10488:                             $checked = ' checked="checked"';
10489:                         }
10490:                     }
10491:                     my $parent_title = $parent;
10492:                     if ($parent eq 'communities') {
10493:                         $parent_title = &mt('Communities');
10494:                     }
10495:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
10496:                               '<input type="checkbox" name="usecategory" value="'.
10497:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
10498:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
10499:                     my $depth = 1;
10500:                     push(@path,$parent);
10501:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
10502:                     pop(@path);
10503:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10504:                     $itemcount ++;
10505:                 }
10506:                 if ($itemcount) {
10507:                     $output = &Apache::loncommon::start_data_table().
10508:                               $table.
10509:                               &Apache::loncommon::end_data_table();
10510:                 }
10511:             }
10512:         }
10513:     }
10514:     return $output;
10515: }
10516: 
10517: =pod
10518: 
10519: =item *&assign_category_rows()
10520: 
10521: Create a datatable row for display of nested categories in a domain,
10522: with checkboxes to allow a course to be categorized,called recursively.
10523: 
10524: Inputs:
10525: 
10526: itemcount - track row number for alternating colors
10527: 
10528: cats - reference to array of arrays/hashes which encapsulates hierarchy of
10529:       categories and subcategories.
10530: 
10531: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
10532: 
10533: parent - parent of current category item
10534: 
10535: path - Array containing all categories back up through the hierarchy from the
10536:        current category to the top level.
10537: 
10538: currcategories - reference to array of current categories assigned to the course
10539: 
10540: Returns: $output (markup to be displayed).
10541: 
10542: =cut
10543: 
10544: sub assign_category_rows {
10545:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
10546:     my ($text,$name,$item,$chgstr);
10547:     if (ref($cats) eq 'ARRAY') {
10548:         my $maxdepth = scalar(@{$cats});
10549:         if (ref($cats->[$depth]) eq 'HASH') {
10550:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10551:                 my $numchildren = @{$cats->[$depth]{$parent}};
10552:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10553:                 $text .= '<td><table class="LC_datatable">';
10554:                 for (my $j=0; $j<$numchildren; $j++) {
10555:                     $name = $cats->[$depth]{$parent}[$j];
10556:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
10557:                     my $deeper = $depth+1;
10558:                     my $checked = '';
10559:                     if (ref($currcategories) eq 'ARRAY') {
10560:                         if (@{$currcategories} > 0) {
10561:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
10562:                                 $checked = ' checked="checked"';
10563:                             }
10564:                         }
10565:                     }
10566:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
10567:                              '<input type="checkbox" name="usecategory" value="'.
10568:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
10569:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
10570:                              '</td><td>';
10571:                     if (ref($path) eq 'ARRAY') {
10572:                         push(@{$path},$name);
10573:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10574:                         pop(@{$path});
10575:                     }
10576:                     $text .= '</td></tr>';
10577:                 }
10578:                 $text .= '</table></td>';
10579:             }
10580:         }
10581:     }
10582:     return $text;
10583: }
10584: 
10585: ############################################################
10586: ############################################################
10587: 
10588: 
10589: sub commit_customrole {
10590:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10591:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10592:                          ($start?', '.&mt('starting').' '.localtime($start):'').
10593:                          ($end?', ending '.localtime($end):'').': <b>'.
10594:               &Apache::lonnet::assigncustomrole(
10595:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10596:                  '</b><br />';
10597:     return $output;
10598: }
10599: 
10600: sub commit_standardrole {
10601:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10602:     my ($output,$logmsg,$linefeed);
10603:     if ($context eq 'auto') {
10604:         $linefeed = "\n";
10605:     } else {
10606:         $linefeed = "<br />\n";
10607:     }  
10608:     if ($three eq 'st') {
10609:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10610:                                          $one,$two,$sec,$context);
10611:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
10612:             ($result eq 'unknown_course') || ($result eq 'refused')) {
10613:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
10614:         } else {
10615:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10616:                ($start?', '.&mt('starting').' '.localtime($start):'').
10617:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10618:             if ($context eq 'auto') {
10619:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10620:             } else {
10621:                $output .= '<b>'.$result.'</b>'.$linefeed.
10622:                &mt('Add to classlist').': <b>ok</b>';
10623:             }
10624:             $output .= $linefeed;
10625:         }
10626:     } else {
10627:         $output = &mt('Assigning').' '.$three.' in '.$url.
10628:                ($start?', '.&mt('starting').' '.localtime($start):'').
10629:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10630:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10631:         if ($context eq 'auto') {
10632:             $output .= $result.$linefeed;
10633:         } else {
10634:             $output .= '<b>'.$result.'</b>'.$linefeed;
10635:         }
10636:     }
10637:     return $output;
10638: }
10639: 
10640: sub commit_studentrole {
10641:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10642:     my ($result,$linefeed,$oldsecurl,$newsecurl);
10643:     if ($context eq 'auto') {
10644:         $linefeed = "\n";
10645:     } else {
10646:         $linefeed = '<br />'."\n";
10647:     }
10648:     if (defined($one) && defined($two)) {
10649:         my $cid=$one.'_'.$two;
10650:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10651:         my $secchange = 0;
10652:         my $expire_role_result;
10653:         my $modify_section_result;
10654:         if ($oldsec ne '-1') { 
10655:             if ($oldsec ne $sec) {
10656:                 $secchange = 1;
10657:                 my $now = time;
10658:                 my $uurl='/'.$cid;
10659:                 $uurl=~s/\_/\//g;
10660:                 if ($oldsec) {
10661:                     $uurl.='/'.$oldsec;
10662:                 }
10663:                 $oldsecurl = $uurl;
10664:                 $expire_role_result = 
10665:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10666:                 if ($env{'request.course.sec'} ne '') { 
10667:                     if ($expire_role_result eq 'refused') {
10668:                         my @roles = ('st');
10669:                         my @statuses = ('previous');
10670:                         my @roledoms = ($one);
10671:                         my $withsec = 1;
10672:                         my %roleshash = 
10673:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10674:                                               \@statuses,\@roles,\@roledoms,$withsec);
10675:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10676:                             my ($oldstart,$oldend) = 
10677:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10678:                             if ($oldend > 0 && $oldend <= $now) {
10679:                                 $expire_role_result = 'ok';
10680:                             }
10681:                         }
10682:                     }
10683:                 }
10684:                 $result = $expire_role_result;
10685:             }
10686:         }
10687:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10688:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10689:             if ($modify_section_result =~ /^ok/) {
10690:                 if ($secchange == 1) {
10691:                     if ($sec eq '') {
10692:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10693:                     } else {
10694:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10695:                     }
10696:                 } elsif ($oldsec eq '-1') {
10697:                     if ($sec eq '') {
10698:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10699:                     } else {
10700:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10701:                     }
10702:                 } else {
10703:                     if ($sec eq '') {
10704:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10705:                     } else {
10706:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10707:                     }
10708:                 }
10709:             } else {
10710:                 if ($secchange) {       
10711:                     $$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;
10712:                 } else {
10713:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10714:                 }
10715:             }
10716:             $result = $modify_section_result;
10717:         } elsif ($secchange == 1) {
10718:             if ($oldsec eq '') {
10719:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10720:             } else {
10721:                 $$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;
10722:             }
10723:             if ($expire_role_result eq 'refused') {
10724:                 my $newsecurl = '/'.$cid;
10725:                 $newsecurl =~ s/\_/\//g;
10726:                 if ($sec ne '') {
10727:                     $newsecurl.='/'.$sec;
10728:                 }
10729:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10730:                     if ($sec eq '') {
10731:                         $$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;
10732:                     } else {
10733:                         $$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;
10734:                     }
10735:                 }
10736:             }
10737:         }
10738:     } else {
10739:         $$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;
10740:         $result = "error: incomplete course id\n";
10741:     }
10742:     return $result;
10743: }
10744: 
10745: ############################################################
10746: ############################################################
10747: 
10748: sub check_clone {
10749:     my ($args,$linefeed) = @_;
10750:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10751:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10752:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10753:     my $clonemsg;
10754:     my $can_clone = 0;
10755:     my $lctype = lc($args->{'crstype'});
10756:     if ($lctype ne 'community') {
10757:         $lctype = 'course';
10758:     }
10759:     if ($clonehome eq 'no_host') {
10760:         if ($args->{'crstype'} eq 'Community') {
10761:             $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'});
10762:         } else {
10763:             $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'});
10764:         }     
10765:     } else {
10766: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10767:         if ($args->{'crstype'} eq 'Community') {
10768:             if ($clonedesc{'type'} ne 'Community') {
10769:                  $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'});
10770:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10771:             }
10772:         }
10773: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10774:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10775: 	    $can_clone = 1;
10776: 	} else {
10777: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10778: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10779: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10780:             if (grep(/^\*$/,@cloners)) {
10781:                 $can_clone = 1;
10782:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10783:                 $can_clone = 1;
10784:             } else {
10785:                 my $ccrole = 'cc';
10786:                 if ($args->{'crstype'} eq 'Community') {
10787:                     $ccrole = 'co';
10788:                 }
10789: 	        my %roleshash =
10790: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10791: 					 $args->{'ccdomain'},
10792:                                          'userroles',['active'],[$ccrole],
10793: 					 [$args->{'clonedomain'}]);
10794: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10795:                     $can_clone = 1;
10796:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10797:                     $can_clone = 1;
10798:                 } else {
10799:                     if ($args->{'crstype'} eq 'Community') {
10800:                         $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'});
10801:                     } else {
10802:                         $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'});
10803:                     }
10804: 	        }
10805: 	    }
10806:         }
10807:     }
10808:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
10809: }
10810: 
10811: sub construct_course {
10812:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10813:     my $outcome;
10814:     my $linefeed =  '<br />'."\n";
10815:     if ($context eq 'auto') {
10816:         $linefeed = "\n";
10817:     }
10818: 
10819: #
10820: # Are we cloning?
10821: #
10822:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
10823:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10824: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10825: 	if ($context ne 'auto') {
10826:             if ($clonemsg ne '') {
10827: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10828:             }
10829: 	}
10830: 	$outcome .= $clonemsg.$linefeed;
10831: 
10832:         if (!$can_clone) {
10833: 	    return (0,$outcome);
10834: 	}
10835:     }
10836: 
10837: #
10838: # Open course
10839: #
10840:     my $crstype = lc($args->{'crstype'});
10841:     my %cenv=();
10842:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10843:                                              $args->{'cdescr'},
10844:                                              $args->{'curl'},
10845:                                              $args->{'course_home'},
10846:                                              $args->{'nonstandard'},
10847:                                              $args->{'crscode'},
10848:                                              $args->{'ccuname'}.':'.
10849:                                              $args->{'ccdomain'},
10850:                                              $args->{'crstype'},
10851:                                              $cnum,$context,$category);
10852: 
10853:     # Note: The testing routines depend on this being output; see 
10854:     # Utils::Course. This needs to at least be output as a comment
10855:     # if anyone ever decides to not show this, and Utils::Course::new
10856:     # will need to be suitably modified.
10857:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10858:     if ($$courseid =~ /^error:/) {
10859:         return (0,$outcome);
10860:     }
10861: 
10862: #
10863: # Check if created correctly
10864: #
10865:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10866:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10867:     if ($crsuhome eq 'no_host') {
10868:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10869:         return (0,$outcome);
10870:     }
10871:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10872: 
10873: #
10874: # Do the cloning
10875: #   
10876:     if ($can_clone && $cloneid) {
10877: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10878: 	if ($context ne 'auto') {
10879: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10880: 	}
10881: 	$outcome .= $clonemsg.$linefeed;
10882: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10883: # Copy all files
10884: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10885: # Restore URL
10886: 	$cenv{'url'}=$oldcenv{'url'};
10887: # Restore title
10888: 	$cenv{'description'}=$oldcenv{'description'};
10889: # Restore creation date, creator and creation context.
10890:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
10891:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
10892:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
10893: # Mark as cloned
10894: 	$cenv{'clonedfrom'}=$cloneid;
10895: # Need to clone grading mode
10896:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10897:         $cenv{'grading'}=$newenv{'grading'};
10898: # Do not clone these environment entries
10899:         &Apache::lonnet::del('environment',
10900:                   ['default_enrollment_start_date',
10901:                    'default_enrollment_end_date',
10902:                    'question.email',
10903:                    'policy.email',
10904:                    'comment.email',
10905:                    'pch.users.denied',
10906:                    'plc.users.denied',
10907:                    'hidefromcat',
10908:                    'categories'],
10909:                    $$crsudom,$$crsunum);
10910:     }
10911: 
10912: #
10913: # Set environment (will override cloned, if existing)
10914: #
10915:     my @sections = ();
10916:     my @xlists = ();
10917:     if ($args->{'crstype'}) {
10918:         $cenv{'type'}=$args->{'crstype'};
10919:     }
10920:     if ($args->{'crsid'}) {
10921:         $cenv{'courseid'}=$args->{'crsid'};
10922:     }
10923:     if ($args->{'crscode'}) {
10924:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10925:     }
10926:     if ($args->{'crsquota'} ne '') {
10927:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10928:     } else {
10929:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10930:     }
10931:     if ($args->{'ccuname'}) {
10932:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10933:                                         ':'.$args->{'ccdomain'};
10934:     } else {
10935:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10936:     }
10937:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10938:     if ($args->{'crssections'}) {
10939:         $cenv{'internal.sectionnums'} = '';
10940:         if ($args->{'crssections'} =~ m/,/) {
10941:             @sections = split/,/,$args->{'crssections'};
10942:         } else {
10943:             $sections[0] = $args->{'crssections'};
10944:         }
10945:         if (@sections > 0) {
10946:             foreach my $item (@sections) {
10947:                 my ($sec,$gp) = split/:/,$item;
10948:                 my $class = $args->{'crscode'}.$sec;
10949:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10950:                 $cenv{'internal.sectionnums'} .= $item.',';
10951:                 unless ($addcheck eq 'ok') {
10952:                     push @badclasses, $class;
10953:                 }
10954:             }
10955:             $cenv{'internal.sectionnums'} =~ s/,$//;
10956:         }
10957:     }
10958: # do not hide course coordinator from staff listing, 
10959: # even if privileged
10960:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10961: # add crosslistings
10962:     if ($args->{'crsxlist'}) {
10963:         $cenv{'internal.crosslistings'}='';
10964:         if ($args->{'crsxlist'} =~ m/,/) {
10965:             @xlists = split/,/,$args->{'crsxlist'};
10966:         } else {
10967:             $xlists[0] = $args->{'crsxlist'};
10968:         }
10969:         if (@xlists > 0) {
10970:             foreach my $item (@xlists) {
10971:                 my ($xl,$gp) = split/:/,$item;
10972:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10973:                 $cenv{'internal.crosslistings'} .= $item.',';
10974:                 unless ($addcheck eq 'ok') {
10975:                     push @badclasses, $xl;
10976:                 }
10977:             }
10978:             $cenv{'internal.crosslistings'} =~ s/,$//;
10979:         }
10980:     }
10981:     if ($args->{'autoadds'}) {
10982:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
10983:     }
10984:     if ($args->{'autodrops'}) {
10985:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
10986:     }
10987: # check for notification of enrollment changes
10988:     my @notified = ();
10989:     if ($args->{'notify_owner'}) {
10990:         if ($args->{'ccuname'} ne '') {
10991:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10992:         }
10993:     }
10994:     if ($args->{'notify_dc'}) {
10995:         if ($uname ne '') { 
10996:             push(@notified,$uname.':'.$udom);
10997:         }
10998:     }
10999:     if (@notified > 0) {
11000:         my $notifylist;
11001:         if (@notified > 1) {
11002:             $notifylist = join(',',@notified);
11003:         } else {
11004:             $notifylist = $notified[0];
11005:         }
11006:         $cenv{'internal.notifylist'} = $notifylist;
11007:     }
11008:     if (@badclasses > 0) {
11009:         my %lt=&Apache::lonlocal::texthash(
11010:                 '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',
11011:                 'dnhr' => 'does not have rights to access enrollment in these classes',
11012:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
11013:         );
11014:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
11015:                            ' ('.$lt{'adby'}.')';
11016:         if ($context eq 'auto') {
11017:             $outcome .= $badclass_msg.$linefeed;
11018:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
11019:             foreach my $item (@badclasses) {
11020:                 if ($context eq 'auto') {
11021:                     $outcome .= " - $item\n";
11022:                 } else {
11023:                     $outcome .= "<li>$item</li>\n";
11024:                 }
11025:             }
11026:             if ($context eq 'auto') {
11027:                 $outcome .= $linefeed;
11028:             } else {
11029:                 $outcome .= "</ul><br /><br /></div>\n";
11030:             }
11031:         } 
11032:     }
11033:     if ($args->{'no_end_date'}) {
11034:         $args->{'endaccess'} = 0;
11035:     }
11036:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
11037:     $cenv{'internal.autoend'}=$args->{'enrollend'};
11038:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
11039:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
11040:     if ($args->{'showphotos'}) {
11041:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
11042:     }
11043:     $cenv{'internal.authtype'} = $args->{'authtype'};
11044:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
11045:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
11046:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
11047:             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'); 
11048:             if ($context eq 'auto') {
11049:                 $outcome .= $krb_msg;
11050:             } else {
11051:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
11052:             }
11053:             $outcome .= $linefeed;
11054:         }
11055:     }
11056:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
11057:        if ($args->{'setpolicy'}) {
11058:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11059:        }
11060:        if ($args->{'setcontent'}) {
11061:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11062:        }
11063:     }
11064:     if ($args->{'reshome'}) {
11065: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
11066: 	$cenv{'reshome'}=~s/\/+$/\//;
11067:     }
11068: #
11069: # course has keyed access
11070: #
11071:     if ($args->{'setkeys'}) {
11072:        $cenv{'keyaccess'}='yes';
11073:     }
11074: # if specified, key authority is not course, but user
11075: # only active if keyaccess is yes
11076:     if ($args->{'keyauth'}) {
11077: 	my ($user,$domain) = split(':',$args->{'keyauth'});
11078: 	$user = &LONCAPA::clean_username($user);
11079: 	$domain = &LONCAPA::clean_username($domain);
11080: 	if ($user ne '' && $domain ne '') {
11081: 	    $cenv{'keyauth'}=$user.':'.$domain;
11082: 	}
11083:     }
11084: 
11085:     if ($args->{'disresdis'}) {
11086:         $cenv{'pch.roles.denied'}='st';
11087:     }
11088:     if ($args->{'disablechat'}) {
11089:         $cenv{'plc.roles.denied'}='st';
11090:     }
11091: 
11092:     # Record we've not yet viewed the Course Initialization Helper for this 
11093:     # course
11094:     $cenv{'course.helper.not.run'} = 1;
11095:     #
11096:     # Use new Randomseed
11097:     #
11098:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
11099:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
11100:     #
11101:     # The encryption code and receipt prefix for this course
11102:     #
11103:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
11104:     $cenv{'internal.encpref'}=100+int(9*rand(99));
11105:     #
11106:     # By default, use standard grading
11107:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
11108: 
11109:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
11110:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
11111: #
11112: # Open all assignments
11113: #
11114:     if ($args->{'openall'}) {
11115:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
11116:        my %storecontent = ($storeunder         => time,
11117:                            $storeunder.'.type' => 'date_start');
11118:        
11119:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
11120:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
11121:    }
11122: #
11123: # Set first page
11124: #
11125:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
11126: 	    || ($cloneid)) {
11127: 	use LONCAPA::map;
11128: 	$outcome .= &mt('Setting first resource').': ';
11129: 
11130: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
11131:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
11132: 
11133:         $outcome .= ($fatal?$errtext:'read ok').' - ';
11134:         my $title; my $url;
11135:         if ($args->{'firstres'} eq 'syl') {
11136: 	    $title=&mt('Syllabus');
11137:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
11138:         } else {
11139:             $title=&mt('Table of Contents');
11140:             $url='/adm/navmaps';
11141:         }
11142: 
11143:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
11144: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
11145: 
11146: 	if ($errtext) { $fatal=2; }
11147:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
11148:     }
11149: 
11150:     return (1,$outcome);
11151: }
11152: 
11153: ############################################################
11154: ############################################################
11155: 
11156: sub course_type {
11157:     my ($cid) = @_;
11158:     if (!defined($cid)) {
11159:         $cid = $env{'request.course.id'};
11160:     }
11161:     if (defined($env{'course.'.$cid.'.type'})) {
11162:         return $env{'course.'.$cid.'.type'};
11163:     } else {
11164:         return 'Course';
11165:     }
11166: }
11167: 
11168: sub group_term {
11169:     my $crstype = &course_type();
11170:     my %names = (
11171:                   'Course' => 'group',
11172:                   'Community' => 'group',
11173:                 );
11174:     return $names{$crstype};
11175: }
11176: 
11177: sub course_types {
11178:     my @types = ('official','unofficial','community');
11179:     my %typename = (
11180:                          official   => 'Official course',
11181:                          unofficial => 'Unofficial course',
11182:                          community  => 'Community',
11183:                    );
11184:     return (\@types,\%typename);
11185: }
11186: 
11187: sub icon {
11188:     my ($file)=@_;
11189:     my $curfext = lc((split(/\./,$file))[-1]);
11190:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
11191:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
11192:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
11193: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
11194: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11195: 	            $curfext.".gif") {
11196: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11197: 		$curfext.".gif";
11198: 	}
11199:     }
11200:     return &lonhttpdurl($iconname);
11201: } 
11202: 
11203: sub lonhttpdurl {
11204: #
11205: # Had been used for "small fry" static images on separate port 8080.
11206: # Modify here if lightweight http functionality desired again.
11207: # Currently eliminated due to increasing firewall issues.
11208: #
11209:     my ($url)=@_;
11210:     return $url;
11211: }
11212: 
11213: sub connection_aborted {
11214:     my ($r)=@_;
11215:     $r->print(" ");$r->rflush();
11216:     my $c = $r->connection;
11217:     return $c->aborted();
11218: }
11219: 
11220: #    Escapes strings that may have embedded 's that will be put into
11221: #    strings as 'strings'.
11222: sub escape_single {
11223:     my ($input) = @_;
11224:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
11225:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
11226:     return $input;
11227: }
11228: 
11229: #  Same as escape_single, but escape's "'s  This 
11230: #  can be used for  "strings"
11231: sub escape_double {
11232:     my ($input) = @_;
11233:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
11234:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
11235:     return $input;
11236: }
11237:  
11238: #   Escapes the last element of a full URL.
11239: sub escape_url {
11240:     my ($url)   = @_;
11241:     my @urlslices = split(/\//, $url,-1);
11242:     my $lastitem = &escape(pop(@urlslices));
11243:     return join('/',@urlslices).'/'.$lastitem;
11244: }
11245: 
11246: sub compare_arrays {
11247:     my ($arrayref1,$arrayref2) = @_;
11248:     my (@difference,%count);
11249:     @difference = ();
11250:     %count = ();
11251:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
11252:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
11253:         foreach my $element (keys(%count)) {
11254:             if ($count{$element} == 1) {
11255:                 push(@difference,$element);
11256:             }
11257:         }
11258:     }
11259:     return @difference;
11260: }
11261: 
11262: # -------------------------------------------------------- Initialize user login
11263: sub init_user_environment {
11264:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
11265:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
11266: 
11267:     my $public=($username eq 'public' && $domain eq 'public');
11268: 
11269: # See if old ID present, if so, remove
11270: 
11271:     my ($filename,$cookie,$userroles);
11272:     my $now=time;
11273: 
11274:     if ($public) {
11275: 	my $max_public=100;
11276: 	my $oldest;
11277: 	my $oldest_time=0;
11278: 	for(my $next=1;$next<=$max_public;$next++) {
11279: 	    if (-e $lonids."/publicuser_$next.id") {
11280: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
11281: 		if ($mtime<$oldest_time || !$oldest_time) {
11282: 		    $oldest_time=$mtime;
11283: 		    $oldest=$next;
11284: 		}
11285: 	    } else {
11286: 		$cookie="publicuser_$next";
11287: 		last;
11288: 	    }
11289: 	}
11290: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
11291:     } else {
11292: 	# if this isn't a robot, kill any existing non-robot sessions
11293: 	if (!$args->{'robot'}) {
11294: 	    opendir(DIR,$lonids);
11295: 	    while ($filename=readdir(DIR)) {
11296: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
11297: 		    unlink($lonids.'/'.$filename);
11298: 		}
11299: 	    }
11300: 	    closedir(DIR);
11301: 	}
11302: # Give them a new cookie
11303: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
11304: 		                   : $now.$$.int(rand(10000)));
11305: 	$cookie="$username\_$id\_$domain\_$authhost";
11306:     
11307: # Initialize roles
11308: 
11309: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
11310:     }
11311: # ------------------------------------ Check browser type and MathML capability
11312: 
11313:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
11314:         $clientunicode,$clientos) = &decode_user_agent($r);
11315: 
11316: # ------------------------------------------------------------- Get environment
11317: 
11318:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
11319:     my ($tmp) = keys(%userenv);
11320:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11321: 	# default remote control to off
11322: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
11323:     } else {
11324: 	undef(%userenv);
11325:     }
11326:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
11327: 	$form->{'interface'}=$userenv{'interface'};
11328:     }
11329:     $env{'environment.remote'}=$userenv{'remote'};
11330:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
11331: 
11332: # --------------- Do not trust query string to be put directly into environment
11333:     foreach my $option ('interface','localpath','localres') {
11334:         $form->{$option}=~s/[\n\r\=]//gs;
11335:     }
11336: # --------------------------------------------------------- Write first profile
11337: 
11338:     {
11339: 	my %initial_env = 
11340: 	    ("user.name"          => $username,
11341: 	     "user.domain"        => $domain,
11342: 	     "user.home"          => $authhost,
11343: 	     "browser.type"       => $clientbrowser,
11344: 	     "browser.version"    => $clientversion,
11345: 	     "browser.mathml"     => $clientmathml,
11346: 	     "browser.unicode"    => $clientunicode,
11347: 	     "browser.os"         => $clientos,
11348: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
11349: 	     "request.course.fn"  => '',
11350: 	     "request.course.uri" => '',
11351: 	     "request.course.sec" => '',
11352: 	     "request.role"       => 'cm',
11353: 	     "request.role.adv"   => $env{'user.adv'},
11354: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
11355: 
11356:         if ($form->{'localpath'}) {
11357: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
11358: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
11359:         }
11360: 	
11361: 	if ($public) {
11362: 	    $initial_env{"environment.remote"} = "off";
11363: 	}
11364: 	if ($form->{'interface'}) {
11365: 	    $form->{'interface'}=~s/\W//gs;
11366: 	    $initial_env{"browser.interface"} = $form->{'interface'};
11367: 	    $env{'browser.interface'}=$form->{'interface'};
11368: 	}
11369:         my %is_adv = ( is_adv => $env{'user.adv'} );
11370:         my %domdef = &Apache::lonnet::get_domain_defaults($domain);
11371: 
11372:         foreach my $tool ('aboutme','blog','portfolio') {
11373:             $userenv{'availabletools.'.$tool} = 
11374:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
11375:                                                   undef,\%userenv,\%domdef,\%is_adv);
11376:         }
11377: 
11378:         foreach my $crstype ('official','unofficial','community') {
11379:             $userenv{'canrequest.'.$crstype} =
11380:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
11381:                                                   'reload','requestcourses',
11382:                                                   \%userenv,\%domdef,\%is_adv);
11383:         }
11384: 
11385: 	$env{'user.environment'} = "$lonids/$cookie.id";
11386: 	
11387: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
11388: 		 &GDBM_WRCREAT(),0640)) {
11389: 	    &_add_to_env(\%disk_env,\%initial_env);
11390: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
11391: 	    &_add_to_env(\%disk_env,$userroles);
11392: 	    if (ref($args->{'extra_env'})) {
11393: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
11394: 	    }
11395: 	    untie(%disk_env);
11396: 	} else {
11397: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
11398: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
11399: 	    return 'error: '.$!;
11400: 	}
11401:     }
11402:     $env{'request.role'}='cm';
11403:     $env{'request.role.adv'}=$env{'user.adv'};
11404:     $env{'browser.type'}=$clientbrowser;
11405: 
11406:     return $cookie;
11407: 
11408: }
11409: 
11410: sub _add_to_env {
11411:     my ($idf,$env_data,$prefix) = @_;
11412:     if (ref($env_data) eq 'HASH') {
11413:         while (my ($key,$value) = each(%$env_data)) {
11414: 	    $idf->{$prefix.$key} = $value;
11415: 	    $env{$prefix.$key}   = $value;
11416:         }
11417:     }
11418: }
11419: 
11420: # --- Get the symbolic name of a problem and the url
11421: sub get_symb {
11422:     my ($request,$silent) = @_;
11423:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11424:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
11425:     if ($symb eq '') {
11426:         if (!$silent) {
11427:             $request->print("Unable to handle ambiguous references:$url:.");
11428:             return ();
11429:         }
11430:     }
11431:     &Apache::lonenc::check_decrypt(\$symb);
11432:     return ($symb);
11433: }
11434: 
11435: # --------------------------------------------------------------Get annotation
11436: 
11437: sub get_annotation {
11438:     my ($symb,$enc) = @_;
11439: 
11440:     my $key = $symb;
11441:     if (!$enc) {
11442:         $key =
11443:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
11444:     }
11445:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
11446:     return $annotation{$key};
11447: }
11448: 
11449: sub clean_symb {
11450:     my ($symb,$delete_enc) = @_;
11451: 
11452:     &Apache::lonenc::check_decrypt(\$symb);
11453:     my $enc = $env{'request.enc'};
11454:     if ($delete_enc) {
11455:         delete($env{'request.enc'});
11456:     }
11457: 
11458:     return ($symb,$enc);
11459: }
11460: 
11461: sub build_release_hashes {
11462:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
11463:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
11464:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
11465:                   (ref($randomizetry) eq 'HASH'));
11466:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
11467:         my ($item,$name,$value) = split(/:/,$key);
11468:         if ($item eq 'parameter') {
11469:             if (ref($checkparms->{$name}) eq 'ARRAY') {
11470:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
11471:                     push(@{$checkparms->{$name}},$value);
11472:                 }
11473:             } else {
11474:                 push(@{$checkparms->{$name}},$value);
11475:             }
11476:         } elsif ($item eq 'resourcetag') {
11477:             if ($name eq 'responsetype') {
11478:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
11479:             }
11480:         } elsif ($item eq 'course') {
11481:             if ($name eq 'crstype') {
11482:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
11483:             }
11484:         }
11485:     }
11486:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
11487:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
11488:     return;
11489: }
11490: 
11491: =pod
11492: 
11493: =back
11494: 
11495: =cut
11496: 
11497: 1;
11498: __END__;
11499: 

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