File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1009: download - view: text, annotated - select for diffs
Sun Jun 5 12:59:47 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Cleaning up accordion

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1009 2011/06/05 12:59:47 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410: // <![CDATA[
  411:     var stdeditbrowser;
  412:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  413:         var url = '/adm/pickstudent?';
  414:         var filter;
  415: 	if (!ignorefilter) {
  416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  417: 	}
  418:         if (filter != null) {
  419:            if (filter != '') {
  420:                url += 'filter='+filter+'&';
  421: 	   }
  422:         }
  423:         url += 'form=' + formname + '&unameelement='+uname+
  424:                                     '&udomelement='+udom+
  425:                                     '&clicker='+clicker;
  426: 	if (roleflag) { url+="&roles=1"; }
  427:         if (courseadvonly) { url+="&courseadvonly=1"; }
  428:         var title = 'Student_Browser';
  429:         var options = 'scrollbars=1,resizable=1,menubar=0';
  430:         options += ',width=700,height=600';
  431:         stdeditbrowser = open(url,title,options,'1');
  432:         stdeditbrowser.focus();
  433:     }
  434: // ]]>
  435: </script>
  436: ENDSTDBRW
  437: }
  438: 
  439: sub resourcebrowser_javascript {
  440:    unless ($env{'request.course.id'}) { return ''; }
  441:    return (<<'ENDRESBRW');
  442: <script type="text/javascript" language="Javascript">
  443: // <![CDATA[
  444:     var reseditbrowser;
  445:     function openresbrowser(formname,reslink) {
  446:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  447:         var title = 'Resource_Browser';
  448:         var options = 'scrollbars=1,resizable=1,menubar=0';
  449:         options += ',width=700,height=500';
  450:         reseditbrowser = open(url,title,options,'1');
  451:         reseditbrowser.focus();
  452:     }
  453: // ]]>
  454: </script>
  455: ENDRESBRW
  456: }
  457: 
  458: sub selectstudent_link {
  459:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  460:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  461:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  462:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  463:    if ($env{'request.course.id'}) {  
  464:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  465: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  466: 					'/'.$env{'request.course.sec'})) {
  467: 	   return '';
  468:        }
  469:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  470:        if ($courseadvonly)  {
  471:            $callargs .= ",'',1,1";
  472:        }
  473:        return '<span class="LC_nobreak">'.
  474:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  475:               &mt('Select User').'</a></span>';
  476:    }
  477:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  478:        $callargs .= ",1"; 
  479:        return '<span class="LC_nobreak">'.
  480:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  481:               &mt('Select User').'</a></span>';
  482:    }
  483:    return '';
  484: }
  485: 
  486: sub selectresource_link {
  487:    my ($form,$reslink,$arg)=@_;
  488:    
  489:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  490:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  491:    unless ($env{'request.course.id'}) { return $arg; }
  492:    return '<span class="LC_nobreak">'.
  493:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  494:               $arg.'</a></span>';
  495: }
  496: 
  497: 
  498: 
  499: sub authorbrowser_javascript {
  500:     return <<"ENDAUTHORBRW";
  501: <script type="text/javascript" language="JavaScript">
  502: // <![CDATA[
  503: var stdeditbrowser;
  504: 
  505: function openauthorbrowser(formname,udom) {
  506:     var url = '/adm/pickauthor?';
  507:     url += 'form='+formname+'&roledom='+udom;
  508:     var title = 'Author_Browser';
  509:     var options = 'scrollbars=1,resizable=1,menubar=0';
  510:     options += ',width=700,height=600';
  511:     stdeditbrowser = open(url,title,options,'1');
  512:     stdeditbrowser.focus();
  513: }
  514: 
  515: // ]]>
  516: </script>
  517: ENDAUTHORBRW
  518: }
  519: 
  520: sub coursebrowser_javascript {
  521:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  522:     my $wintitle = 'Course_Browser';
  523:     if ($crstype eq 'Community') {
  524:         $wintitle = 'Community_Browser';
  525:     }
  526:     my $id_functions = &javascript_index_functions();
  527:     my $output = '
  528: <script type="text/javascript" language="JavaScript">
  529: // <![CDATA[
  530:     var stdeditbrowser;'."\n";
  531: 
  532:     $output .= <<"ENDSTDBRW";
  533:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  534:         var url = '/adm/pickcourse?';
  535:         var formid = getFormIdByName(formname);
  536:         var domainfilter = getDomainFromSelectbox(formname,udom);
  537:         if (domainfilter != null) {
  538:            if (domainfilter != '') {
  539:                url += 'domainfilter='+domainfilter+'&';
  540: 	   }
  541:         }
  542:         url += 'form=' + formname + '&cnumelement='+uname+
  543: 	                            '&cdomelement='+udom+
  544:                                     '&cnameelement='+desc;
  545:         if (extra_element !=null && extra_element != '') {
  546:             if (formname == 'rolechoice' || formname == 'studentform') {
  547:                 url += '&roleelement='+extra_element;
  548:                 if (domainfilter == null || domainfilter == '') {
  549:                     url += '&domainfilter='+extra_element;
  550:                 }
  551:             }
  552:             else {
  553:                 if (formname == 'portform') {
  554:                     url += '&setroles='+extra_element;
  555:                 } else {
  556:                     if (formname == 'rules') {
  557:                         url += '&fixeddom='+extra_element; 
  558:                     }
  559:                 }
  560:             }     
  561:         }
  562:         if (type != null && type != '') {
  563:             url += '&type='+type;
  564:         }
  565:         if (type_elem != null && type_elem != '') {
  566:             url += '&typeelement='+type_elem;
  567:         }
  568:         if (formname == 'ccrs') {
  569:             var ownername = document.forms[formid].ccuname.value;
  570:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  571:             url += '&cloner='+ownername+':'+ownerdom;
  572:         }
  573:         if (multflag !=null && multflag != '') {
  574:             url += '&multiple='+multflag;
  575:         }
  576:         var title = '$wintitle';
  577:         var options = 'scrollbars=1,resizable=1,menubar=0';
  578:         options += ',width=700,height=600';
  579:         stdeditbrowser = open(url,title,options,'1');
  580:         stdeditbrowser.focus();
  581:     }
  582: $id_functions
  583: ENDSTDBRW
  584:     if (($sec_element ne '') || ($role_element ne '')) {
  585:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  586:     }
  587:     $output .= '
  588: // ]]>
  589: </script>';
  590:     return $output;
  591: }
  592: 
  593: sub javascript_index_functions {
  594:     return <<"ENDJS";
  595: 
  596: function getFormIdByName(formname) {
  597:     for (var i=0;i<document.forms.length;i++) {
  598:         if (document.forms[i].name == formname) {
  599:             return i;
  600:         }
  601:     }
  602:     return -1;
  603: }
  604: 
  605: function getIndexByName(formid,item) {
  606:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  607:         if (document.forms[formid].elements[i].name == item) {
  608:             return i;
  609:         }
  610:     }
  611:     return -1;
  612: }
  613: 
  614: function getDomainFromSelectbox(formname,udom) {
  615:     var userdom;
  616:     var formid = getFormIdByName(formname);
  617:     if (formid > -1) {
  618:         var domid = getIndexByName(formid,udom);
  619:         if (domid > -1) {
  620:             if (document.forms[formid].elements[domid].type == 'select-one') {
  621:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  622:             }
  623:             if (document.forms[formid].elements[domid].type == 'hidden') {
  624:                 userdom=document.forms[formid].elements[domid].value;
  625:             }
  626:         }
  627:     }
  628:     return userdom;
  629: }
  630: 
  631: ENDJS
  632: 
  633: }
  634: 
  635: sub userbrowser_javascript {
  636:     my $id_functions = &javascript_index_functions();
  637:     return <<"ENDUSERBRW";
  638: 
  639: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  640:     var url = '/adm/pickuser?';
  641:     var userdom = getDomainFromSelectbox(formname,udom);
  642:     if (userdom != null) {
  643:        if (userdom != '') {
  644:            url += 'srchdom='+userdom+'&';
  645:        }
  646:     }
  647:     url += 'form=' + formname + '&unameelement='+uname+
  648:                                 '&udomelement='+udom+
  649:                                 '&ulastelement='+ulast+
  650:                                 '&ufirstelement='+ufirst+
  651:                                 '&uemailelement='+uemail+
  652:                                 '&hideudomelement='+hideudom+
  653:                                 '&coursedom='+crsdom;
  654:     if ((caller != null) && (caller != undefined)) {
  655:         url += '&caller='+caller;
  656:     }
  657:     var title = 'User_Browser';
  658:     var options = 'scrollbars=1,resizable=1,menubar=0';
  659:     options += ',width=700,height=600';
  660:     var stdeditbrowser = open(url,title,options,'1');
  661:     stdeditbrowser.focus();
  662: }
  663: 
  664: function fix_domain (formname,udom,origdom,uname) {
  665:     var formid = getFormIdByName(formname);
  666:     if (formid > -1) {
  667:         var unameid = getIndexByName(formid,uname);
  668:         var domid = getIndexByName(formid,udom);
  669:         var hidedomid = getIndexByName(formid,origdom);
  670:         if (hidedomid > -1) {
  671:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  672:             var unameval = document.forms[formid].elements[unameid].value;
  673:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  674:                 if (domid > -1) {
  675:                     var slct = document.forms[formid].elements[domid];
  676:                     if (slct.type == 'select-one') {
  677:                         var i;
  678:                         for (i=0;i<slct.length;i++) {
  679:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  680:                         }
  681:                     }
  682:                     if (slct.type == 'hidden') {
  683:                         slct.value = fixeddom;
  684:                     }
  685:                 }
  686:             }
  687:         }
  688:     }
  689:     return;
  690: }
  691: 
  692: $id_functions
  693: ENDUSERBRW
  694: }
  695: 
  696: sub setsec_javascript {
  697:     my ($sec_element,$formname,$role_element) = @_;
  698:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  699:         $communityrolestr);
  700:     if ($role_element ne '') {
  701:         my @allroles = ('st','ta','ep','in','ad');
  702:         foreach my $crstype ('Course','Community') {
  703:             if ($crstype eq 'Community') {
  704:                 foreach my $role (@allroles) {
  705:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  706:                 }
  707:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  708:             } else {
  709:                 foreach my $role (@allroles) {
  710:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  711:                 }
  712:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  713:             }
  714:         }
  715:         $rolestr = '"'.join('","',@allroles).'"';
  716:         $courserolestr = '"'.join('","',@courserolenames).'"';
  717:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  718:     }
  719:     my $setsections = qq|
  720: function setSect(sectionlist) {
  721:     var sectionsArray = new Array();
  722:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  723:         sectionsArray = sectionlist.split(",");
  724:     }
  725:     var numSections = sectionsArray.length;
  726:     document.$formname.$sec_element.length = 0;
  727:     if (numSections == 0) {
  728:         document.$formname.$sec_element.multiple=false;
  729:         document.$formname.$sec_element.size=1;
  730:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  731:     } else {
  732:         if (numSections == 1) {
  733:             document.$formname.$sec_element.multiple=false;
  734:             document.$formname.$sec_element.size=1;
  735:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  736:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  737:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  738:         } else {
  739:             for (var i=0; i<numSections; i++) {
  740:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  741:             }
  742:             document.$formname.$sec_element.multiple=true
  743:             if (numSections < 3) {
  744:                 document.$formname.$sec_element.size=numSections;
  745:             } else {
  746:                 document.$formname.$sec_element.size=3;
  747:             }
  748:             document.$formname.$sec_element.options[0].selected = false
  749:         }
  750:     }
  751: }
  752: 
  753: function setRole(crstype) {
  754: |;
  755:     if ($role_element eq '') {
  756:         $setsections .= '    return;
  757: }
  758: ';
  759:     } else {
  760:         $setsections .= qq|
  761:     var elementLength = document.$formname.$role_element.length;
  762:     var allroles = Array($rolestr);
  763:     var courserolenames = Array($courserolestr);
  764:     var communityrolenames = Array($communityrolestr);
  765:     if (elementLength != undefined) {
  766:         if (document.$formname.$role_element.options[5].value == 'cc') {
  767:             if (crstype == 'Course') {
  768:                 return;
  769:             } else {
  770:                 allroles[5] = 'co';
  771:                 for (var i=0; i<6; i++) {
  772:                     document.$formname.$role_element.options[i].value = allroles[i];
  773:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  774:                 }
  775:             }
  776:         } else {
  777:             if (crstype == 'Community') {
  778:                 return;
  779:             } else {
  780:                 allroles[5] = 'cc';
  781:                 for (var i=0; i<6; i++) {
  782:                     document.$formname.$role_element.options[i].value = allroles[i];
  783:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  784:                 }
  785:             }
  786:         }
  787:     }
  788:     return;
  789: }
  790: |;
  791:     }
  792:     return $setsections;
  793: }
  794: 
  795: sub selectcourse_link {
  796:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  797:        $typeelement) = @_;
  798:    my $type = $selecttype;
  799:    my $linktext = &mt('Select Course');
  800:    if ($selecttype eq 'Community') {
  801:        $linktext = &mt('Select Community');
  802:    } elsif ($selecttype eq 'Course/Community') {
  803:        $linktext = &mt('Select Course/Community');
  804:        $type = '';
  805:    }
  806:    return '<span class="LC_nobreak">'
  807:          ."<a href='"
  808:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  809:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  810:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  811:          ."'>".$linktext.'</a>'
  812:          .'</span>';
  813: }
  814: 
  815: sub selectauthor_link {
  816:    my ($form,$udom)=@_;
  817:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  818:           &mt('Select Author').'</a>';
  819: }
  820: 
  821: sub selectuser_link {
  822:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  823:         $coursedom,$linktext,$caller) = @_;
  824:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  825:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  826:            ');">'.$linktext.'</a>';
  827: }
  828: 
  829: sub check_uncheck_jscript {
  830:     my $jscript = <<"ENDSCRT";
  831: function checkAll(field) {
  832:     if (field.length > 0) {
  833:         for (i = 0; i < field.length; i++) {
  834:             field[i].checked = true ;
  835:         }
  836:     } else {
  837:         field.checked = true
  838:     }
  839: }
  840:  
  841: function uncheckAll(field) {
  842:     if (field.length > 0) {
  843:         for (i = 0; i < field.length; i++) {
  844:             field[i].checked = false ;
  845:         }
  846:     } else {
  847:         field.checked = false ;
  848:     }
  849: }
  850: ENDSCRT
  851:     return $jscript;
  852: }
  853: 
  854: sub select_timezone {
  855:    my ($name,$selected,$onchange,$includeempty)=@_;
  856:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  857:    if ($includeempty) {
  858:        $output .= '<option value=""';
  859:        if (($selected eq '') || ($selected eq 'local')) {
  860:            $output .= ' selected="selected" ';
  861:        }
  862:        $output .= '> </option>';
  863:    }
  864:    my @timezones = DateTime::TimeZone->all_names;
  865:    foreach my $tzone (@timezones) {
  866:        $output.= '<option value="'.$tzone.'"';
  867:        if ($tzone eq $selected) {
  868:            $output.=' selected="selected"';
  869:        }
  870:        $output.=">$tzone</option>\n";
  871:    }
  872:    $output.="</select>";
  873:    return $output;
  874: }
  875: 
  876: sub select_datelocale {
  877:     my ($name,$selected,$onchange,$includeempty)=@_;
  878:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  879:     if ($includeempty) {
  880:         $output .= '<option value=""';
  881:         if ($selected eq '') {
  882:             $output .= ' selected="selected" ';
  883:         }
  884:         $output .= '> </option>';
  885:     }
  886:     my (@possibles,%locale_names);
  887:     my @locales = DateTime::Locale::Catalog::Locales;
  888:     foreach my $locale (@locales) {
  889:         if (ref($locale) eq 'HASH') {
  890:             my $id = $locale->{'id'};
  891:             if ($id ne '') {
  892:                 my $en_terr = $locale->{'en_territory'};
  893:                 my $native_terr = $locale->{'native_territory'};
  894:                 my @languages = &Apache::lonlocal::preferred_languages();
  895:                 if (grep(/^en$/,@languages) || !@languages) {
  896:                     if ($en_terr ne '') {
  897:                         $locale_names{$id} = '('.$en_terr.')';
  898:                     } elsif ($native_terr ne '') {
  899:                         $locale_names{$id} = $native_terr;
  900:                     }
  901:                 } else {
  902:                     if ($native_terr ne '') {
  903:                         $locale_names{$id} = $native_terr.' ';
  904:                     } elsif ($en_terr ne '') {
  905:                         $locale_names{$id} = '('.$en_terr.')';
  906:                     }
  907:                 }
  908:                 push (@possibles,$id);
  909:             }
  910:         }
  911:     }
  912:     foreach my $item (sort(@possibles)) {
  913:         $output.= '<option value="'.$item.'"';
  914:         if ($item eq $selected) {
  915:             $output.=' selected="selected"';
  916:         }
  917:         $output.=">$item";
  918:         if ($locale_names{$item} ne '') {
  919:             $output.="  $locale_names{$item}</option>\n";
  920:         }
  921:         $output.="</option>\n";
  922:     }
  923:     $output.="</select>";
  924:     return $output;
  925: }
  926: 
  927: sub select_language {
  928:     my ($name,$selected,$includeempty) = @_;
  929:     my %langchoices;
  930:     if ($includeempty) {
  931:         %langchoices = ('' => 'No language preference');
  932:     }
  933:     foreach my $id (&languageids()) {
  934:         my $code = &supportedlanguagecode($id);
  935:         if ($code) {
  936:             $langchoices{$code} = &plainlanguagedescription($id);
  937:         }
  938:     }
  939:     return &select_form($selected,$name,\%langchoices);
  940: }
  941: 
  942: =pod
  943: 
  944: =item * &linked_select_forms(...)
  945: 
  946: linked_select_forms returns a string containing a <script></script> block
  947: and html for two <select> menus.  The select menus will be linked in that
  948: changing the value of the first menu will result in new values being placed
  949: in the second menu.  The values in the select menu will appear in alphabetical
  950: order unless a defined order is provided.
  951: 
  952: linked_select_forms takes the following ordered inputs:
  953: 
  954: =over 4
  955: 
  956: =item * $formname, the name of the <form> tag
  957: 
  958: =item * $middletext, the text which appears between the <select> tags
  959: 
  960: =item * $firstdefault, the default value for the first menu
  961: 
  962: =item * $firstselectname, the name of the first <select> tag
  963: 
  964: =item * $secondselectname, the name of the second <select> tag
  965: 
  966: =item * $hashref, a reference to a hash containing the data for the menus.
  967: 
  968: =item * $menuorder, the order of values in the first menu
  969: 
  970: =back 
  971: 
  972: Below is an example of such a hash.  Only the 'text', 'default', and 
  973: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  974: values for the first select menu.  The text that coincides with the 
  975: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  976: and text for the second menu are given in the hash pointed to by 
  977: $menu{$choice1}->{'select2'}.  
  978: 
  979:  my %menu = ( A1 => { text =>"Choice A1" ,
  980:                        default => "B3",
  981:                        select2 => { 
  982:                            B1 => "Choice B1",
  983:                            B2 => "Choice B2",
  984:                            B3 => "Choice B3",
  985:                            B4 => "Choice B4"
  986:                            },
  987:                        order => ['B4','B3','B1','B2'],
  988:                    },
  989:                A2 => { text =>"Choice A2" ,
  990:                        default => "C2",
  991:                        select2 => { 
  992:                            C1 => "Choice C1",
  993:                            C2 => "Choice C2",
  994:                            C3 => "Choice C3"
  995:                            },
  996:                        order => ['C2','C1','C3'],
  997:                    },
  998:                A3 => { text =>"Choice A3" ,
  999:                        default => "D6",
 1000:                        select2 => { 
 1001:                            D1 => "Choice D1",
 1002:                            D2 => "Choice D2",
 1003:                            D3 => "Choice D3",
 1004:                            D4 => "Choice D4",
 1005:                            D5 => "Choice D5",
 1006:                            D6 => "Choice D6",
 1007:                            D7 => "Choice D7"
 1008:                            },
 1009:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1010:                    }
 1011:                );
 1012: 
 1013: =cut
 1014: 
 1015: sub linked_select_forms {
 1016:     my ($formname,
 1017:         $middletext,
 1018:         $firstdefault,
 1019:         $firstselectname,
 1020:         $secondselectname, 
 1021:         $hashref,
 1022:         $menuorder,
 1023:         ) = @_;
 1024:     my $second = "document.$formname.$secondselectname";
 1025:     my $first = "document.$formname.$firstselectname";
 1026:     # output the javascript to do the changing
 1027:     my $result = '';
 1028:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1029:     $result.="// <![CDATA[\n";
 1030:     $result.="var select2data = new Object();\n";
 1031:     $" = '","';
 1032:     my $debug = '';
 1033:     foreach my $s1 (sort(keys(%$hashref))) {
 1034:         $result.="select2data.d_$s1 = new Object();\n";        
 1035:         $result.="select2data.d_$s1.def = new String('".
 1036:             $hashref->{$s1}->{'default'}."');\n";
 1037:         $result.="select2data.d_$s1.values = new Array(";
 1038:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1039:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1040:             @s2values = @{$hashref->{$s1}->{'order'}};
 1041:         }
 1042:         $result.="\"@s2values\");\n";
 1043:         $result.="select2data.d_$s1.texts = new Array(";        
 1044:         my @s2texts;
 1045:         foreach my $value (@s2values) {
 1046:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1047:         }
 1048:         $result.="\"@s2texts\");\n";
 1049:     }
 1050:     $"=' ';
 1051:     $result.= <<"END";
 1052: 
 1053: function select1_changed() {
 1054:     // Determine new choice
 1055:     var newvalue = "d_" + $first.value;
 1056:     // update select2
 1057:     var values     = select2data[newvalue].values;
 1058:     var texts      = select2data[newvalue].texts;
 1059:     var select2def = select2data[newvalue].def;
 1060:     var i;
 1061:     // out with the old
 1062:     for (i = 0; i < $second.options.length; i++) {
 1063:         $second.options[i] = null;
 1064:     }
 1065:     // in with the nuclear
 1066:     for (i=0;i<values.length; i++) {
 1067:         $second.options[i] = new Option(values[i]);
 1068:         $second.options[i].value = values[i];
 1069:         $second.options[i].text = texts[i];
 1070:         if (values[i] == select2def) {
 1071:             $second.options[i].selected = true;
 1072:         }
 1073:     }
 1074: }
 1075: // ]]>
 1076: </script>
 1077: END
 1078:     # output the initial values for the selection lists
 1079:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1080:     my @order = sort(keys(%{$hashref}));
 1081:     if (ref($menuorder) eq 'ARRAY') {
 1082:         @order = @{$menuorder};
 1083:     }
 1084:     foreach my $value (@order) {
 1085:         $result.="    <option value=\"$value\" ";
 1086:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1087:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1088:     }
 1089:     $result .= "</select>\n";
 1090:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1091:     $result .= $middletext;
 1092:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1093:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1094:     
 1095:     my @secondorder = sort(keys(%select2));
 1096:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1097:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1098:     }
 1099:     foreach my $value (@secondorder) {
 1100:         $result.="    <option value=\"$value\" ";        
 1101:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1102:         $result.=">".&mt($select2{$value})."</option>\n";
 1103:     }
 1104:     $result .= "</select>\n";
 1105:     #    return $debug;
 1106:     return $result;
 1107: }   #  end of sub linked_select_forms {
 1108: 
 1109: =pod
 1110: 
 1111: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1112: 
 1113: Returns a string corresponding to an HTML link to the given help
 1114: $topic, where $topic corresponds to the name of a .tex file in
 1115: /home/httpd/html/adm/help/tex, with underscores replaced by
 1116: spaces. 
 1117: 
 1118: $text will optionally be linked to the same topic, allowing you to
 1119: link text in addition to the graphic. If you do not want to link
 1120: text, but wish to specify one of the later parameters, pass an
 1121: empty string. 
 1122: 
 1123: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1124: the link will not open a new window. If false, the link will open
 1125: a new window using Javascript. (Default is false.) 
 1126: 
 1127: $width and $height are optional numerical parameters that will
 1128: override the width and height of the popped up window, which may
 1129: be useful for certain help topics with big pictures included.
 1130: 
 1131: $imgid is the id of the img tag used for the help icon. This may be
 1132: used in a javascript call to switch the image src.  See 
 1133: lonhtmlcommon::htmlareaselectactive() for an example.
 1134: 
 1135: =cut
 1136: 
 1137: sub help_open_topic {
 1138:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1139:     $text = "" if (not defined $text);
 1140:     $stayOnPage = 0 if (not defined $stayOnPage);
 1141:     $width = 350 if (not defined $width);
 1142:     $height = 400 if (not defined $height);
 1143:     my $filename = $topic;
 1144:     $filename =~ s/ /_/g;
 1145: 
 1146:     my $template = "";
 1147:     my $link;
 1148:     
 1149:     $topic=~s/\W/\_/g;
 1150: 
 1151:     if (!$stayOnPage) {
 1152: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1153:     } else {
 1154: 	$link = "/adm/help/${filename}.hlp";
 1155:     }
 1156: 
 1157:     # Add the text
 1158:     if ($text ne "") {	
 1159: 	$template.='<span class="LC_help_open_topic">'
 1160:                   .'<a target="_top" href="'.$link.'">'
 1161:                   .$text.'</a>';
 1162:     }
 1163: 
 1164:     # (Always) Add the graphic
 1165:     my $title = &mt('Online Help');
 1166:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1167:     if ($imgid ne '') {
 1168:         $imgid = ' id="'.$imgid.'"';
 1169:     }
 1170:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1171:               .'<img src="'.$helpicon.'" border="0"'
 1172:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1173:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1174:               .' /></a>';
 1175:     if ($text ne "") {	
 1176:         $template.='</span>';
 1177:     }
 1178:     return $template;
 1179: 
 1180: }
 1181: 
 1182: # This is a quicky function for Latex cheatsheet editing, since it 
 1183: # appears in at least four places
 1184: sub helpLatexCheatsheet {
 1185:     my ($topic,$text,$not_author) = @_;
 1186:     my $out;
 1187:     my $addOther = '';
 1188:     if ($topic) {
 1189: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1190: 							       undef, undef, 600).
 1191: 								   '</span> ';
 1192:     }
 1193:     $out = '<span>' # Start cheatsheet
 1194: 	  .$addOther
 1195:           .'<span>'
 1196: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1197: 					       undef,undef,600)
 1198: 	  .'</span> <span>'
 1199: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1200: 					       undef,undef,600)
 1201: 	  .'</span>';
 1202:     unless ($not_author) {
 1203:         $out .= ' <span>'
 1204: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1205: 	                                            undef,undef,600)
 1206: 	       .'</span>';
 1207:     }
 1208:     $out .= '</span>'; # End cheatsheet
 1209:     return $out;
 1210: }
 1211: 
 1212: sub general_help {
 1213:     my $helptopic='Student_Intro';
 1214:     if ($env{'request.role'}=~/^(ca|au)/) {
 1215: 	$helptopic='Authoring_Intro';
 1216:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1217: 	$helptopic='Course_Coordination_Intro';
 1218:     } elsif ($env{'request.role'}=~/^dc/) {
 1219:         $helptopic='Domain_Coordination_Intro';
 1220:     }
 1221:     return $helptopic;
 1222: }
 1223: 
 1224: sub update_help_link {
 1225:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1226:     my $origurl = $ENV{'REQUEST_URI'};
 1227:     $origurl=~s|^/~|/priv/|;
 1228:     my $timestamp = time;
 1229:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1230:         $$datum = &escape($$datum);
 1231:     }
 1232: 
 1233:     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";
 1234:     my $output .= <<"ENDOUTPUT";
 1235: <script type="text/javascript">
 1236: // <![CDATA[
 1237: banner_link = '$banner_link';
 1238: // ]]>
 1239: </script>
 1240: ENDOUTPUT
 1241:     return $output;
 1242: }
 1243: 
 1244: # now just updates the help link and generates a blue icon
 1245: sub help_open_menu {
 1246:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1247: 	= @_;    
 1248:     $stayOnPage = 1;
 1249:     my $output;
 1250:     if ($component_help) {
 1251: 	if (!$text) {
 1252: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1253: 				       $width,$height);
 1254: 	} else {
 1255: 	    my $help_text;
 1256: 	    $help_text=&unescape($topic);
 1257: 	    $output='<table><tr><td>'.
 1258: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1259: 				 $width,$height).'</td></tr></table>';
 1260: 	}
 1261:     }
 1262:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1263:     return $output.$banner_link;
 1264: }
 1265: 
 1266: sub top_nav_help {
 1267:     my ($text) = @_;
 1268:     $text = &mt($text);
 1269:     my $stay_on_page = 1;
 1270: 
 1271:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1272: 	                     : "javascript:helpMenu('open')";
 1273:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1274: 
 1275:     my $title = &mt('Get help');
 1276: 
 1277:     return <<"END";
 1278: $banner_link
 1279:  <a href="$link" title="$title">$text</a>
 1280: END
 1281: }
 1282: 
 1283: sub help_menu_js {
 1284:     my ($text) = @_;
 1285:     my $stayOnPage = 1;
 1286:     my $width = 620;
 1287:     my $height = 600;
 1288:     my $helptopic=&general_help();
 1289:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1290:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1291:     my $start_page =
 1292:         &Apache::loncommon::start_page('Help Menu', undef,
 1293: 				       {'frameset'    => 1,
 1294: 					'js_ready'    => 1,
 1295: 					'add_entries' => {
 1296: 					    'border' => '0',
 1297: 					    'rows'   => "110,*",},});
 1298:     my $end_page =
 1299:         &Apache::loncommon::end_page({'frameset' => 1,
 1300: 				      'js_ready' => 1,});
 1301: 
 1302:     my $template .= <<"ENDTEMPLATE";
 1303: <script type="text/javascript">
 1304: // <![CDATA[
 1305: // <!-- BEGIN LON-CAPA Internal
 1306: var banner_link = '';
 1307: function helpMenu(target) {
 1308:     var caller = this;
 1309:     if (target == 'open') {
 1310:         var newWindow = null;
 1311:         try {
 1312:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1313:         }
 1314:         catch(error) {
 1315:             writeHelp(caller);
 1316:             return;
 1317:         }
 1318:         if (newWindow) {
 1319:             caller = newWindow;
 1320:         }
 1321:     }
 1322:     writeHelp(caller);
 1323:     return;
 1324: }
 1325: function writeHelp(caller) {
 1326:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1327:     caller.document.close()
 1328:     caller.focus()
 1329: }
 1330: // END LON-CAPA Internal -->
 1331: // ]]>
 1332: </script>
 1333: ENDTEMPLATE
 1334:     return $template;
 1335: }
 1336: 
 1337: sub help_open_bug {
 1338:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1339:     unless ($env{'user.adv'}) { return ''; }
 1340:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1341:     $text = "" if (not defined $text);
 1342: 	$stayOnPage=1;
 1343:     $width = 600 if (not defined $width);
 1344:     $height = 600 if (not defined $height);
 1345: 
 1346:     $topic=~s/\W+/\+/g;
 1347:     my $link='';
 1348:     my $template='';
 1349:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1350: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1351:     if (!$stayOnPage)
 1352:     {
 1353: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1354:     }
 1355:     else
 1356:     {
 1357: 	$link = $url;
 1358:     }
 1359:     # Add the text
 1360:     if ($text ne "")
 1361:     {
 1362: 	$template .= 
 1363:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1364:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1365:     }
 1366: 
 1367:     # Add the graphic
 1368:     my $title = &mt('Report a Bug');
 1369:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1370:     $template .= <<"ENDTEMPLATE";
 1371:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1372: ENDTEMPLATE
 1373:     if ($text ne '') { $template.='</td></tr></table>' };
 1374:     return $template;
 1375: 
 1376: }
 1377: 
 1378: sub help_open_faq {
 1379:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1380:     unless ($env{'user.adv'}) { return ''; }
 1381:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1382:     $text = "" if (not defined $text);
 1383: 	$stayOnPage=1;
 1384:     $width = 350 if (not defined $width);
 1385:     $height = 400 if (not defined $height);
 1386: 
 1387:     $topic=~s/\W+/\+/g;
 1388:     my $link='';
 1389:     my $template='';
 1390:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1391:     if (!$stayOnPage)
 1392:     {
 1393: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1394:     }
 1395:     else
 1396:     {
 1397: 	$link = $url;
 1398:     }
 1399: 
 1400:     # Add the text
 1401:     if ($text ne "")
 1402:     {
 1403: 	$template .= 
 1404:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1405:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1406:     }
 1407: 
 1408:     # Add the graphic
 1409:     my $title = &mt('View the FAQ');
 1410:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1411:     $template .= <<"ENDTEMPLATE";
 1412:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1413: ENDTEMPLATE
 1414:     if ($text ne '') { $template.='</td></tr></table>' };
 1415:     return $template;
 1416: 
 1417: }
 1418: 
 1419: ###############################################################
 1420: ###############################################################
 1421: 
 1422: =pod
 1423: 
 1424: =item * &change_content_javascript():
 1425: 
 1426: This and the next function allow you to create small sections of an
 1427: otherwise static HTML page that you can update on the fly with
 1428: Javascript, even in Netscape 4.
 1429: 
 1430: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1431: must be written to the HTML page once. It will prove the Javascript
 1432: function "change(name, content)". Calling the change function with the
 1433: name of the section 
 1434: you want to update, matching the name passed to C<changable_area>, and
 1435: the new content you want to put in there, will put the content into
 1436: that area.
 1437: 
 1438: B<Note>: Netscape 4 only reserves enough space for the changable area
 1439: to contain room for the original contents. You need to "make space"
 1440: for whatever changes you wish to make, and be B<sure> to check your
 1441: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1442: it's adequate for updating a one-line status display, but little more.
 1443: This script will set the space to 100% width, so you only need to
 1444: worry about height in Netscape 4.
 1445: 
 1446: Modern browsers are much less limiting, and if you can commit to the
 1447: user not using Netscape 4, this feature may be used freely with
 1448: pretty much any HTML.
 1449: 
 1450: =cut
 1451: 
 1452: sub change_content_javascript {
 1453:     # If we're on Netscape 4, we need to use Layer-based code
 1454:     if ($env{'browser.type'} eq 'netscape' &&
 1455: 	$env{'browser.version'} =~ /^4\./) {
 1456: 	return (<<NETSCAPE4);
 1457: 	function change(name, content) {
 1458: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1459: 	    doc.open();
 1460: 	    doc.write(content);
 1461: 	    doc.close();
 1462: 	}
 1463: NETSCAPE4
 1464:     } else {
 1465: 	# Otherwise, we need to use semi-standards-compliant code
 1466: 	# (technically, "innerHTML" isn't standard but the equivalent
 1467: 	# is really scary, and every useful browser supports it
 1468: 	return (<<DOMBASED);
 1469: 	function change(name, content) {
 1470: 	    element = document.getElementById(name);
 1471: 	    element.innerHTML = content;
 1472: 	}
 1473: DOMBASED
 1474:     }
 1475: }
 1476: 
 1477: =pod
 1478: 
 1479: =item * &changable_area($name,$origContent):
 1480: 
 1481: This provides a "changable area" that can be modified on the fly via
 1482: the Javascript code provided in C<change_content_javascript>. $name is
 1483: the name you will use to reference the area later; do not repeat the
 1484: same name on a given HTML page more then once. $origContent is what
 1485: the area will originally contain, which can be left blank.
 1486: 
 1487: =cut
 1488: 
 1489: sub changable_area {
 1490:     my ($name, $origContent) = @_;
 1491: 
 1492:     if ($env{'browser.type'} eq 'netscape' &&
 1493: 	$env{'browser.version'} =~ /^4\./) {
 1494: 	# If this is netscape 4, we need to use the Layer tag
 1495: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1496:     } else {
 1497: 	return "<span id='$name'>$origContent</span>";
 1498:     }
 1499: }
 1500: 
 1501: =pod
 1502: 
 1503: =item * &viewport_geometry_js 
 1504: 
 1505: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1506: 
 1507: =cut
 1508: 
 1509: 
 1510: sub viewport_geometry_js { 
 1511:     return <<"GEOMETRY";
 1512: var Geometry = {};
 1513: function init_geometry() {
 1514:     if (Geometry.init) { return };
 1515:     Geometry.init=1;
 1516:     if (window.innerHeight) {
 1517:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1518:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1519:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1520:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1521:     }
 1522:     else if (document.documentElement && document.documentElement.clientHeight) {
 1523:         Geometry.getViewportHeight =
 1524:             function() { return document.documentElement.clientHeight; };
 1525:         Geometry.getViewportWidth =
 1526:             function() { return document.documentElement.clientWidth; };
 1527: 
 1528:         Geometry.getHorizontalScroll =
 1529:             function() { return document.documentElement.scrollLeft; };
 1530:         Geometry.getVerticalScroll =
 1531:             function() { return document.documentElement.scrollTop; };
 1532:     }
 1533:     else if (document.body.clientHeight) {
 1534:         Geometry.getViewportHeight =
 1535:             function() { return document.body.clientHeight; };
 1536:         Geometry.getViewportWidth =
 1537:             function() { return document.body.clientWidth; };
 1538:         Geometry.getHorizontalScroll =
 1539:             function() { return document.body.scrollLeft; };
 1540:         Geometry.getVerticalScroll =
 1541:             function() { return document.body.scrollTop; };
 1542:     }
 1543: }
 1544: 
 1545: GEOMETRY
 1546: }
 1547: 
 1548: =pod
 1549: 
 1550: =item * &viewport_size_js()
 1551: 
 1552: 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. 
 1553: 
 1554: =cut
 1555: 
 1556: sub viewport_size_js {
 1557:     my $geometry = &viewport_geometry_js();
 1558:     return <<"DIMS";
 1559: 
 1560: $geometry
 1561: 
 1562: function getViewportDims(width,height) {
 1563:     init_geometry();
 1564:     width.value = Geometry.getViewportWidth();
 1565:     height.value = Geometry.getViewportHeight();
 1566:     return;
 1567: }
 1568: 
 1569: DIMS
 1570: }
 1571: 
 1572: =pod
 1573: 
 1574: =item * &resize_textarea_js()
 1575: 
 1576: emits the needed javascript to resize a textarea to be as big as possible
 1577: 
 1578: creates a function resize_textrea that takes two IDs first should be
 1579: the id of the element to resize, second should be the id of a div that
 1580: surrounds everything that comes after the textarea, this routine needs
 1581: to be attached to the <body> for the onload and onresize events.
 1582: 
 1583: =back
 1584: 
 1585: =cut
 1586: 
 1587: sub resize_textarea_js {
 1588:     my $geometry = &viewport_geometry_js();
 1589:     return <<"RESIZE";
 1590:     <script type="text/javascript">
 1591: // <![CDATA[
 1592: $geometry
 1593: 
 1594: function getX(element) {
 1595:     var x = 0;
 1596:     while (element) {
 1597: 	x += element.offsetLeft;
 1598: 	element = element.offsetParent;
 1599:     }
 1600:     return x;
 1601: }
 1602: function getY(element) {
 1603:     var y = 0;
 1604:     while (element) {
 1605: 	y += element.offsetTop;
 1606: 	element = element.offsetParent;
 1607:     }
 1608:     return y;
 1609: }
 1610: 
 1611: 
 1612: function resize_textarea(textarea_id,bottom_id) {
 1613:     init_geometry();
 1614:     var textarea        = document.getElementById(textarea_id);
 1615:     //alert(textarea);
 1616: 
 1617:     var textarea_top    = getY(textarea);
 1618:     var textarea_height = textarea.offsetHeight;
 1619:     var bottom          = document.getElementById(bottom_id);
 1620:     var bottom_top      = getY(bottom);
 1621:     var bottom_height   = bottom.offsetHeight;
 1622:     var window_height   = Geometry.getViewportHeight();
 1623:     var fudge           = 23;
 1624:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1625:     if (new_height < 300) {
 1626: 	new_height = 300;
 1627:     }
 1628:     textarea.style.height=new_height+'px';
 1629: }
 1630: // ]]>
 1631: </script>
 1632: RESIZE
 1633: 
 1634: }
 1635: 
 1636: =pod
 1637: 
 1638: =head1 Excel and CSV file utility routines
 1639: 
 1640: =over 4
 1641: 
 1642: =cut
 1643: 
 1644: ###############################################################
 1645: ###############################################################
 1646: 
 1647: =pod
 1648: 
 1649: =item * &csv_translate($text) 
 1650: 
 1651: Translate $text to allow it to be output as a 'comma separated values' 
 1652: format.
 1653: 
 1654: =cut
 1655: 
 1656: ###############################################################
 1657: ###############################################################
 1658: sub csv_translate {
 1659:     my $text = shift;
 1660:     $text =~ s/\"/\"\"/g;
 1661:     $text =~ s/\n/ /g;
 1662:     return $text;
 1663: }
 1664: 
 1665: ###############################################################
 1666: ###############################################################
 1667: 
 1668: =pod
 1669: 
 1670: =item * &define_excel_formats()
 1671: 
 1672: Define some commonly used Excel cell formats.
 1673: 
 1674: Currently supported formats:
 1675: 
 1676: =over 4
 1677: 
 1678: =item header
 1679: 
 1680: =item bold
 1681: 
 1682: =item h1
 1683: 
 1684: =item h2
 1685: 
 1686: =item h3
 1687: 
 1688: =item h4
 1689: 
 1690: =item i
 1691: 
 1692: =item date
 1693: 
 1694: =back
 1695: 
 1696: Inputs: $workbook
 1697: 
 1698: Returns: $format, a hash reference.
 1699: 
 1700: =cut
 1701: 
 1702: ###############################################################
 1703: ###############################################################
 1704: sub define_excel_formats {
 1705:     my ($workbook) = @_;
 1706:     my $format;
 1707:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1708:                                                 bottom    => 1,
 1709:                                                 align     => 'center');
 1710:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1711:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1712:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1713:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1714:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1715:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1716:     $format->{'date'} = $workbook->add_format(num_format=>
 1717:                                             'mm/dd/yyyy hh:mm:ss');
 1718:     return $format;
 1719: }
 1720: 
 1721: ###############################################################
 1722: ###############################################################
 1723: 
 1724: =pod
 1725: 
 1726: =item * &create_workbook()
 1727: 
 1728: Create an Excel worksheet.  If it fails, output message on the
 1729: request object and return undefs.
 1730: 
 1731: Inputs: Apache request object
 1732: 
 1733: Returns (undef) on failure, 
 1734:     Excel worksheet object, scalar with filename, and formats 
 1735:     from &Apache::loncommon::define_excel_formats on success
 1736: 
 1737: =cut
 1738: 
 1739: ###############################################################
 1740: ###############################################################
 1741: sub create_workbook {
 1742:     my ($r) = @_;
 1743:         #
 1744:     # Create the excel spreadsheet
 1745:     my $filename = '/prtspool/'.
 1746:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1747:         time.'_'.rand(1000000000).'.xls';
 1748:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1749:     if (! defined($workbook)) {
 1750:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1751:         $r->print(
 1752:             '<p class="LC_error">'
 1753:            .&mt('Problems occurred in creating the new Excel file.')
 1754:            .' '.&mt('This error has been logged.')
 1755:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1756:            .'</p>'
 1757:         );
 1758:         return (undef);
 1759:     }
 1760:     #
 1761:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1762:     #
 1763:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1764:     return ($workbook,$filename,$format);
 1765: }
 1766: 
 1767: ###############################################################
 1768: ###############################################################
 1769: 
 1770: =pod
 1771: 
 1772: =item * &create_text_file()
 1773: 
 1774: Create a file to write to and eventually make available to the user.
 1775: If file creation fails, outputs an error message on the request object and 
 1776: return undefs.
 1777: 
 1778: Inputs: Apache request object, and file suffix
 1779: 
 1780: Returns (undef) on failure, 
 1781:     Filehandle and filename on success.
 1782: 
 1783: =cut
 1784: 
 1785: ###############################################################
 1786: ###############################################################
 1787: sub create_text_file {
 1788:     my ($r,$suffix) = @_;
 1789:     if (! defined($suffix)) { $suffix = 'txt'; };
 1790:     my $fh;
 1791:     my $filename = '/prtspool/'.
 1792:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1793:         time.'_'.rand(1000000000).'.'.$suffix;
 1794:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1795:     if (! defined($fh)) {
 1796:         $r->log_error("Couldn't open $filename for output $!");
 1797:         $r->print(
 1798:             '<p class="LC_error">'
 1799:            .&mt('Problems occurred in creating the output file.')
 1800:            .' '.&mt('This error has been logged.')
 1801:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1802:            .'</p>'
 1803:         );
 1804:     }
 1805:     return ($fh,$filename)
 1806: }
 1807: 
 1808: 
 1809: =pod 
 1810: 
 1811: =back
 1812: 
 1813: =cut
 1814: 
 1815: ###############################################################
 1816: ##        Home server <option> list generating code          ##
 1817: ###############################################################
 1818: 
 1819: # ------------------------------------------
 1820: 
 1821: sub domain_select {
 1822:     my ($name,$value,$multiple)=@_;
 1823:     my %domains=map { 
 1824: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1825:     } &Apache::lonnet::all_domains();
 1826:     if ($multiple) {
 1827: 	$domains{''}=&mt('Any domain');
 1828: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1829: 	return &multiple_select_form($name,$value,4,\%domains);
 1830:     } else {
 1831: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1832: 	return &select_form($name,$value,\%domains);
 1833:     }
 1834: }
 1835: 
 1836: #-------------------------------------------
 1837: 
 1838: =pod
 1839: 
 1840: =head1 Routines for form select boxes
 1841: 
 1842: =over 4
 1843: 
 1844: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1845: 
 1846: Returns a string containing a <select> element int multiple mode
 1847: 
 1848: 
 1849: Args:
 1850:   $name - name of the <select> element
 1851:   $value - scalar or array ref of values that should already be selected
 1852:   $size - number of rows long the select element is
 1853:   $hash - the elements should be 'option' => 'shown text'
 1854:           (shown text should already have been &mt())
 1855:   $order - (optional) array ref of the order to show the elements in
 1856: 
 1857: =cut
 1858: 
 1859: #-------------------------------------------
 1860: sub multiple_select_form {
 1861:     my ($name,$value,$size,$hash,$order)=@_;
 1862:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1863:     my $output='';
 1864:     if (! defined($size)) {
 1865:         $size = 4;
 1866:         if (scalar(keys(%$hash))<4) {
 1867:             $size = scalar(keys(%$hash));
 1868:         }
 1869:     }
 1870:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1871:     my @order;
 1872:     if (ref($order) eq 'ARRAY')  {
 1873:         @order = @{$order};
 1874:     } else {
 1875:         @order = sort(keys(%$hash));
 1876:     }
 1877:     if (exists($$hash{'select_form_order'})) {
 1878:         @order = @{$$hash{'select_form_order'}};
 1879:     }
 1880:         
 1881:     foreach my $key (@order) {
 1882:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1883:         $output.='selected="selected" ' if ($selected{$key});
 1884:         $output.='>'.$hash->{$key}."</option>\n";
 1885:     }
 1886:     $output.="</select>\n";
 1887:     return $output;
 1888: }
 1889: 
 1890: #-------------------------------------------
 1891: 
 1892: =pod
 1893: 
 1894: =item * &select_form($defdom,$name,$hashref,$onchange)
 1895: 
 1896: Returns a string containing a <select name='$name' size='1'> form to 
 1897: allow a user to select options from a ref to a hash containing:
 1898: option_name => displayed text. An optional $onchange can include
 1899: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1900: 
 1901: See lonrights.pm for an example invocation and use.
 1902: 
 1903: =cut
 1904: 
 1905: #-------------------------------------------
 1906: sub select_form {
 1907:     my ($def,$name,$hashref,$onchange) = @_;
 1908:     return unless (ref($hashref) eq 'HASH');
 1909:     if ($onchange) {
 1910:         $onchange = ' onchange="'.$onchange.'"';
 1911:     }
 1912:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1913:     my @keys;
 1914:     if (exists($hashref->{'select_form_order'})) {
 1915: 	@keys=@{$hashref->{'select_form_order'}};
 1916:     } else {
 1917: 	@keys=sort(keys(%{$hashref}));
 1918:     }
 1919:     foreach my $key (@keys) {
 1920:         $selectform.=
 1921: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1922:             ($key eq $def ? 'selected="selected" ' : '').
 1923:                 ">".$hashref->{$key}."</option>\n";
 1924:     }
 1925:     $selectform.="</select>";
 1926:     return $selectform;
 1927: }
 1928: 
 1929: # For display filters
 1930: 
 1931: sub display_filter {
 1932:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1933:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1934:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1935: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1936: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1937: 	   '</label></span> <span class="LC_nobreak">'.
 1938:            &mt('Filter [_1]',
 1939: 	   &select_form($env{'form.displayfilter'},
 1940: 			'displayfilter',
 1941: 			{'currentfolder' => 'Current folder/page',
 1942: 			 'containing' => 'Containing phrase',
 1943: 			 'none' => 'None'})).
 1944: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1945: }
 1946: 
 1947: sub gradeleveldescription {
 1948:     my $gradelevel=shift;
 1949:     my %gradelevels=(0 => 'Not specified',
 1950: 		     1 => 'Grade 1',
 1951: 		     2 => 'Grade 2',
 1952: 		     3 => 'Grade 3',
 1953: 		     4 => 'Grade 4',
 1954: 		     5 => 'Grade 5',
 1955: 		     6 => 'Grade 6',
 1956: 		     7 => 'Grade 7',
 1957: 		     8 => 'Grade 8',
 1958: 		     9 => 'Grade 9',
 1959: 		     10 => 'Grade 10',
 1960: 		     11 => 'Grade 11',
 1961: 		     12 => 'Grade 12',
 1962: 		     13 => 'Grade 13',
 1963: 		     14 => '100 Level',
 1964: 		     15 => '200 Level',
 1965: 		     16 => '300 Level',
 1966: 		     17 => '400 Level',
 1967: 		     18 => 'Graduate Level');
 1968:     return &mt($gradelevels{$gradelevel});
 1969: }
 1970: 
 1971: sub select_level_form {
 1972:     my ($deflevel,$name)=@_;
 1973:     unless ($deflevel) { $deflevel=0; }
 1974:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1975:     for (my $i=0; $i<=18; $i++) {
 1976:         $selectform.="<option value=\"$i\" ".
 1977:             ($i==$deflevel ? 'selected="selected" ' : '').
 1978:                 ">".&gradeleveldescription($i)."</option>\n";
 1979:     }
 1980:     $selectform.="</select>";
 1981:     return $selectform;
 1982: }
 1983: 
 1984: #-------------------------------------------
 1985: 
 1986: =pod
 1987: 
 1988: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 1989: 
 1990: Returns a string containing a <select name='$name' size='1'> form to 
 1991: allow a user to select the domain to preform an operation in.  
 1992: See loncreateuser.pm for an example invocation and use.
 1993: 
 1994: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1995: selected");
 1996: 
 1997: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1998: 
 1999: 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.
 2000: 
 2001: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2002: 
 2003: =cut
 2004: 
 2005: #-------------------------------------------
 2006: sub select_dom_form {
 2007:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2008:     if ($onchange) {
 2009:         $onchange = ' onchange="'.$onchange.'"';
 2010:     }
 2011:     my @domains;
 2012:     if (ref($incdoms) eq 'ARRAY') {
 2013:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2014:     } else {
 2015:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2016:     }
 2017:     if ($includeempty) { @domains=('',@domains); }
 2018:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2019:     foreach my $dom (@domains) {
 2020:         $selectdomain.="<option value=\"$dom\" ".
 2021:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2022:         if ($showdomdesc) {
 2023:             if ($dom ne '') {
 2024:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2025:                 if ($domdesc ne '') {
 2026:                     $selectdomain .= ' ('.$domdesc.')';
 2027:                 }
 2028:             } 
 2029:         }
 2030:         $selectdomain .= "</option>\n";
 2031:     }
 2032:     $selectdomain.="</select>";
 2033:     return $selectdomain;
 2034: }
 2035: 
 2036: #-------------------------------------------
 2037: 
 2038: =pod
 2039: 
 2040: =item * &home_server_form_item($domain,$name,$defaultflag)
 2041: 
 2042: input: 4 arguments (two required, two optional) - 
 2043:     $domain - domain of new user
 2044:     $name - name of form element
 2045:     $default - Value of 'default' causes a default item to be first 
 2046:                             option, and selected by default. 
 2047:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2048:                             if 1 server found, or default, if 0 found.
 2049: output: returns 2 items: 
 2050: (a) form element which contains either:
 2051:    (i) <select name="$name">
 2052:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2053:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2054:        </select>
 2055:        form item if there are multiple library servers in $domain, or
 2056:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2057:        if there is only one library server in $domain.
 2058: 
 2059: (b) number of library servers found.
 2060: 
 2061: See loncreateuser.pm for example of use.
 2062: 
 2063: =cut
 2064: 
 2065: #-------------------------------------------
 2066: sub home_server_form_item {
 2067:     my ($domain,$name,$default,$hide) = @_;
 2068:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2069:     my $result;
 2070:     my $numlib = keys(%servers);
 2071:     if ($numlib > 1) {
 2072:         $result .= '<select name="'.$name.'" />'."\n";
 2073:         if ($default) {
 2074:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2075:                        '</option>'."\n";
 2076:         }
 2077:         foreach my $hostid (sort(keys(%servers))) {
 2078:             $result.= '<option value="'.$hostid.'">'.
 2079: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2080:         }
 2081:         $result .= '</select>'."\n";
 2082:     } elsif ($numlib == 1) {
 2083:         my $hostid;
 2084:         foreach my $item (keys(%servers)) {
 2085:             $hostid = $item;
 2086:         }
 2087:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2088:                    $hostid.'" />';
 2089:                    if (!$hide) {
 2090:                        $result .= $hostid.' '.$servers{$hostid};
 2091:                    }
 2092:                    $result .= "\n";
 2093:     } elsif ($default) {
 2094:         $result .= '<input type="hidden" name="'.$name.
 2095:                    '" value="default" />';
 2096:                    if (!$hide) {
 2097:                        $result .= &mt('default');
 2098:                    }
 2099:                    $result .= "\n";
 2100:     }
 2101:     return ($result,$numlib);
 2102: }
 2103: 
 2104: =pod
 2105: 
 2106: =back 
 2107: 
 2108: =cut
 2109: 
 2110: ###############################################################
 2111: ##                  Decoding User Agent                      ##
 2112: ###############################################################
 2113: 
 2114: =pod
 2115: 
 2116: =head1 Decoding the User Agent
 2117: 
 2118: =over 4
 2119: 
 2120: =item * &decode_user_agent()
 2121: 
 2122: Inputs: $r
 2123: 
 2124: Outputs:
 2125: 
 2126: =over 4
 2127: 
 2128: =item * $httpbrowser
 2129: 
 2130: =item * $clientbrowser
 2131: 
 2132: =item * $clientversion
 2133: 
 2134: =item * $clientmathml
 2135: 
 2136: =item * $clientunicode
 2137: 
 2138: =item * $clientos
 2139: 
 2140: =back
 2141: 
 2142: =back 
 2143: 
 2144: =cut
 2145: 
 2146: ###############################################################
 2147: ###############################################################
 2148: sub decode_user_agent {
 2149:     my ($r)=@_;
 2150:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2151:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2152:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2153:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2154:     my $clientbrowser='unknown';
 2155:     my $clientversion='0';
 2156:     my $clientmathml='';
 2157:     my $clientunicode='0';
 2158:     for (my $i=0;$i<=$#browsertype;$i++) {
 2159:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2160: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2161: 	    $clientbrowser=$bname;
 2162:             $httpbrowser=~/$vreg/i;
 2163: 	    $clientversion=$1;
 2164:             $clientmathml=($clientversion>=$minv);
 2165:             $clientunicode=($clientversion>=$univ);
 2166: 	}
 2167:     }
 2168:     my $clientos='unknown';
 2169:     if (($httpbrowser=~/linux/i) ||
 2170:         ($httpbrowser=~/unix/i) ||
 2171:         ($httpbrowser=~/ux/i) ||
 2172:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2173:     if (($httpbrowser=~/vax/i) ||
 2174:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2175:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2176:     if (($httpbrowser=~/mac/i) ||
 2177:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2178:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2179:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2180:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2181:             $clientunicode,$clientos,);
 2182: }
 2183: 
 2184: ###############################################################
 2185: ##    Authentication changing form generation subroutines    ##
 2186: ###############################################################
 2187: ##
 2188: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2189: ## hash, and have reasonable default values.
 2190: ##
 2191: ##    formname = the name given in the <form> tag.
 2192: #-------------------------------------------
 2193: 
 2194: =pod
 2195: 
 2196: =head1 Authentication Routines
 2197: 
 2198: =over 4
 2199: 
 2200: =item * &authform_xxxxxx()
 2201: 
 2202: The authform_xxxxxx subroutines provide javascript and html forms which 
 2203: handle some of the conveniences required for authentication forms.  
 2204: This is not an optimal method, but it works.  
 2205: 
 2206: =over 4
 2207: 
 2208: =item * authform_header
 2209: 
 2210: =item * authform_authorwarning
 2211: 
 2212: =item * authform_nochange
 2213: 
 2214: =item * authform_kerberos
 2215: 
 2216: =item * authform_internal
 2217: 
 2218: =item * authform_filesystem
 2219: 
 2220: =back
 2221: 
 2222: See loncreateuser.pm for invocation and use examples.
 2223: 
 2224: =cut
 2225: 
 2226: #-------------------------------------------
 2227: sub authform_header{  
 2228:     my %in = (
 2229:         formname => 'cu',
 2230:         kerb_def_dom => '',
 2231:         @_,
 2232:     );
 2233:     $in{'formname'} = 'document.' . $in{'formname'};
 2234:     my $result='';
 2235: 
 2236: #---------------------------------------------- Code for upper case translation
 2237:     my $Javascript_toUpperCase;
 2238:     unless ($in{kerb_def_dom}) {
 2239:         $Javascript_toUpperCase =<<"END";
 2240:         switch (choice) {
 2241:            case 'krb': currentform.elements[choicearg].value =
 2242:                currentform.elements[choicearg].value.toUpperCase();
 2243:                break;
 2244:            default:
 2245:         }
 2246: END
 2247:     } else {
 2248:         $Javascript_toUpperCase = "";
 2249:     }
 2250: 
 2251:     my $radioval = "'nochange'";
 2252:     if (defined($in{'curr_authtype'})) {
 2253:         if ($in{'curr_authtype'} ne '') {
 2254:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2255:         }
 2256:     }
 2257:     my $argfield = 'null';
 2258:     if (defined($in{'mode'})) {
 2259:         if ($in{'mode'} eq 'modifycourse')  {
 2260:             if (defined($in{'curr_autharg'})) {
 2261:                 if ($in{'curr_autharg'} ne '') {
 2262:                     $argfield = "'$in{'curr_autharg'}'";
 2263:                 }
 2264:             }
 2265:         }
 2266:     }
 2267: 
 2268:     $result.=<<"END";
 2269: var current = new Object();
 2270: current.radiovalue = $radioval;
 2271: current.argfield = $argfield;
 2272: 
 2273: function changed_radio(choice,currentform) {
 2274:     var choicearg = choice + 'arg';
 2275:     // If a radio button in changed, we need to change the argfield
 2276:     if (current.radiovalue != choice) {
 2277:         current.radiovalue = choice;
 2278:         if (current.argfield != null) {
 2279:             currentform.elements[current.argfield].value = '';
 2280:         }
 2281:         if (choice == 'nochange') {
 2282:             current.argfield = null;
 2283:         } else {
 2284:             current.argfield = choicearg;
 2285:             switch(choice) {
 2286:                 case 'krb': 
 2287:                     currentform.elements[current.argfield].value = 
 2288:                         "$in{'kerb_def_dom'}";
 2289:                 break;
 2290:               default:
 2291:                 break;
 2292:             }
 2293:         }
 2294:     }
 2295:     return;
 2296: }
 2297: 
 2298: function changed_text(choice,currentform) {
 2299:     var choicearg = choice + 'arg';
 2300:     if (currentform.elements[choicearg].value !='') {
 2301:         $Javascript_toUpperCase
 2302:         // clear old field
 2303:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2304:             currentform.elements[current.argfield].value = '';
 2305:         }
 2306:         current.argfield = choicearg;
 2307:     }
 2308:     set_auth_radio_buttons(choice,currentform);
 2309:     return;
 2310: }
 2311: 
 2312: function set_auth_radio_buttons(newvalue,currentform) {
 2313:     var numauthchoices = currentform.login.length;
 2314:     if (typeof numauthchoices  == "undefined") {
 2315:         return;
 2316:     } 
 2317:     var i=0;
 2318:     while (i < numauthchoices) {
 2319:         if (currentform.login[i].value == newvalue) { break; }
 2320:         i++;
 2321:     }
 2322:     if (i == numauthchoices) {
 2323:         return;
 2324:     }
 2325:     current.radiovalue = newvalue;
 2326:     currentform.login[i].checked = true;
 2327:     return;
 2328: }
 2329: END
 2330:     return $result;
 2331: }
 2332: 
 2333: sub authform_authorwarning{
 2334:     my $result='';
 2335:     $result='<i>'.
 2336:         &mt('As a general rule, only authors or co-authors should be '.
 2337:             'filesystem authenticated '.
 2338:             '(which allows access to the server filesystem).')."</i>\n";
 2339:     return $result;
 2340: }
 2341: 
 2342: sub authform_nochange{  
 2343:     my %in = (
 2344:               formname => 'document.cu',
 2345:               kerb_def_dom => 'MSU.EDU',
 2346:               @_,
 2347:           );
 2348:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2349:     my $result;
 2350:     if (keys(%can_assign) == 0) {
 2351:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2352:     } else {
 2353:         $result = '<label>'.&mt('[_1] Do not change login data',
 2354:                   '<input type="radio" name="login" value="nochange" '.
 2355:                   'checked="checked" onclick="'.
 2356:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2357: 	    '</label>';
 2358:     }
 2359:     return $result;
 2360: }
 2361: 
 2362: sub authform_kerberos {
 2363:     my %in = (
 2364:               formname => 'document.cu',
 2365:               kerb_def_dom => 'MSU.EDU',
 2366:               kerb_def_auth => 'krb4',
 2367:               @_,
 2368:               );
 2369:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2370:         $autharg,$jscall);
 2371:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2372:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2373:        $check5 = ' checked="checked"';
 2374:     } else {
 2375:        $check4 = ' checked="checked"';
 2376:     }
 2377:     $krbarg = $in{'kerb_def_dom'};
 2378:     if (defined($in{'curr_authtype'})) {
 2379:         if ($in{'curr_authtype'} eq 'krb') {
 2380:             $krbcheck = ' checked="checked"';
 2381:             if (defined($in{'mode'})) {
 2382:                 if ($in{'mode'} eq 'modifyuser') {
 2383:                     $krbcheck = '';
 2384:                 }
 2385:             }
 2386:             if (defined($in{'curr_kerb_ver'})) {
 2387:                 if ($in{'curr_krb_ver'} eq '5') {
 2388:                     $check5 = ' checked="checked"';
 2389:                     $check4 = '';
 2390:                 } else {
 2391:                     $check4 = ' checked="checked"';
 2392:                     $check5 = '';
 2393:                 }
 2394:             }
 2395:             if (defined($in{'curr_autharg'})) {
 2396:                 $krbarg = $in{'curr_autharg'};
 2397:             }
 2398:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2399:                 if (defined($in{'curr_autharg'})) {
 2400:                     $result = 
 2401:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2402:         $in{'curr_autharg'},$krbver);
 2403:                 } else {
 2404:                     $result =
 2405:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2406:                 }
 2407:                 return $result; 
 2408:             }
 2409:         }
 2410:     } else {
 2411:         if ($authnum == 1) {
 2412:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2413:         }
 2414:     }
 2415:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2416:         return;
 2417:     } elsif ($authtype eq '') {
 2418:         if (defined($in{'mode'})) {
 2419:             if ($in{'mode'} eq 'modifycourse') {
 2420:                 if ($authnum == 1) {
 2421:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2422:                 }
 2423:             }
 2424:         }
 2425:     }
 2426:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2427:     if ($authtype eq '') {
 2428:         $authtype = '<input type="radio" name="login" value="krb" '.
 2429:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2430:                     $krbcheck.' />';
 2431:     }
 2432:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2433:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2434:          $in{'curr_authtype'} eq 'krb5') ||
 2435:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2436:          $in{'curr_authtype'} eq 'krb4')) {
 2437:         $result .= &mt
 2438:         ('[_1] Kerberos authenticated with domain [_2] '.
 2439:          '[_3] Version 4 [_4] Version 5 [_5]',
 2440:          '<label>'.$authtype,
 2441:          '</label><input type="text" size="10" name="krbarg" '.
 2442:              'value="'.$krbarg.'" '.
 2443:              'onchange="'.$jscall.'" />',
 2444:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2445:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2446: 	 '</label>');
 2447:     } elsif ($can_assign{'krb4'}) {
 2448:         $result .= &mt
 2449:         ('[_1] Kerberos authenticated with domain [_2] '.
 2450:          '[_3] Version 4 [_4]',
 2451:          '<label>'.$authtype,
 2452:          '</label><input type="text" size="10" name="krbarg" '.
 2453:              'value="'.$krbarg.'" '.
 2454:              'onchange="'.$jscall.'" />',
 2455:          '<label><input type="hidden" name="krbver" value="4" />',
 2456:          '</label>');
 2457:     } elsif ($can_assign{'krb5'}) {
 2458:         $result .= &mt
 2459:         ('[_1] Kerberos authenticated with domain [_2] '.
 2460:          '[_3] Version 5 [_4]',
 2461:          '<label>'.$authtype,
 2462:          '</label><input type="text" size="10" name="krbarg" '.
 2463:              'value="'.$krbarg.'" '.
 2464:              'onchange="'.$jscall.'" />',
 2465:          '<label><input type="hidden" name="krbver" value="5" />',
 2466:          '</label>');
 2467:     }
 2468:     return $result;
 2469: }
 2470: 
 2471: sub authform_internal{  
 2472:     my %in = (
 2473:                 formname => 'document.cu',
 2474:                 kerb_def_dom => 'MSU.EDU',
 2475:                 @_,
 2476:                 );
 2477:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2478:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2479:     if (defined($in{'curr_authtype'})) {
 2480:         if ($in{'curr_authtype'} eq 'int') {
 2481:             if ($can_assign{'int'}) {
 2482:                 $intcheck = 'checked="checked" ';
 2483:                 if (defined($in{'mode'})) {
 2484:                     if ($in{'mode'} eq 'modifyuser') {
 2485:                         $intcheck = '';
 2486:                     }
 2487:                 }
 2488:                 if (defined($in{'curr_autharg'})) {
 2489:                     $intarg = $in{'curr_autharg'};
 2490:                 }
 2491:             } else {
 2492:                 $result = &mt('Currently internally authenticated.');
 2493:                 return $result;
 2494:             }
 2495:         }
 2496:     } else {
 2497:         if ($authnum == 1) {
 2498:             $authtype = '<input type="hidden" name="login" value="int" />';
 2499:         }
 2500:     }
 2501:     if (!$can_assign{'int'}) {
 2502:         return;
 2503:     } elsif ($authtype eq '') {
 2504:         if (defined($in{'mode'})) {
 2505:             if ($in{'mode'} eq 'modifycourse') {
 2506:                 if ($authnum == 1) {
 2507:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2508:                 }
 2509:             }
 2510:         }
 2511:     }
 2512:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2513:     if ($authtype eq '') {
 2514:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2515:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2516:     }
 2517:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2518:                $intarg.'" onchange="'.$jscall.'" />';
 2519:     $result = &mt
 2520:         ('[_1] Internally authenticated (with initial password [_2])',
 2521:          '<label>'.$authtype,'</label>'.$autharg);
 2522:     $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>';
 2523:     return $result;
 2524: }
 2525: 
 2526: sub authform_local{  
 2527:     my %in = (
 2528:               formname => 'document.cu',
 2529:               kerb_def_dom => 'MSU.EDU',
 2530:               @_,
 2531:               );
 2532:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2533:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2534:     if (defined($in{'curr_authtype'})) {
 2535:         if ($in{'curr_authtype'} eq 'loc') {
 2536:             if ($can_assign{'loc'}) {
 2537:                 $loccheck = 'checked="checked" ';
 2538:                 if (defined($in{'mode'})) {
 2539:                     if ($in{'mode'} eq 'modifyuser') {
 2540:                         $loccheck = '';
 2541:                     }
 2542:                 }
 2543:                 if (defined($in{'curr_autharg'})) {
 2544:                     $locarg = $in{'curr_autharg'};
 2545:                 }
 2546:             } else {
 2547:                 $result = &mt('Currently using local (institutional) authentication.');
 2548:                 return $result;
 2549:             }
 2550:         }
 2551:     } else {
 2552:         if ($authnum == 1) {
 2553:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2554:         }
 2555:     }
 2556:     if (!$can_assign{'loc'}) {
 2557:         return;
 2558:     } elsif ($authtype eq '') {
 2559:         if (defined($in{'mode'})) {
 2560:             if ($in{'mode'} eq 'modifycourse') {
 2561:                 if ($authnum == 1) {
 2562:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2563:                 }
 2564:             }
 2565:         }
 2566:     }
 2567:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2568:     if ($authtype eq '') {
 2569:         $authtype = '<input type="radio" name="login" value="loc" '.
 2570:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2571:                     $jscall.'" />';
 2572:     }
 2573:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2574:                $locarg.'" onchange="'.$jscall.'" />';
 2575:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2576:                   '<label>'.$authtype,'</label>'.$autharg);
 2577:     return $result;
 2578: }
 2579: 
 2580: sub authform_filesystem{  
 2581:     my %in = (
 2582:               formname => 'document.cu',
 2583:               kerb_def_dom => 'MSU.EDU',
 2584:               @_,
 2585:               );
 2586:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2587:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2588:     if (defined($in{'curr_authtype'})) {
 2589:         if ($in{'curr_authtype'} eq 'fsys') {
 2590:             if ($can_assign{'fsys'}) {
 2591:                 $fsyscheck = 'checked="checked" ';
 2592:                 if (defined($in{'mode'})) {
 2593:                     if ($in{'mode'} eq 'modifyuser') {
 2594:                         $fsyscheck = '';
 2595:                     }
 2596:                 }
 2597:             } else {
 2598:                 $result = &mt('Currently Filesystem Authenticated.');
 2599:                 return $result;
 2600:             }           
 2601:         }
 2602:     } else {
 2603:         if ($authnum == 1) {
 2604:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2605:         }
 2606:     }
 2607:     if (!$can_assign{'fsys'}) {
 2608:         return;
 2609:     } elsif ($authtype eq '') {
 2610:         if (defined($in{'mode'})) {
 2611:             if ($in{'mode'} eq 'modifycourse') {
 2612:                 if ($authnum == 1) {
 2613:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2614:                 }
 2615:             }
 2616:         }
 2617:     }
 2618:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2619:     if ($authtype eq '') {
 2620:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2621:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2622:                     $jscall.'" />';
 2623:     }
 2624:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2625:                ' onchange="'.$jscall.'" />';
 2626:     $result = &mt
 2627:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2628:          '<label><input type="radio" name="login" value="fsys" '.
 2629:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2630:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2631:                   'onchange="'.$jscall.'" />');
 2632:     return $result;
 2633: }
 2634: 
 2635: sub get_assignable_auth {
 2636:     my ($dom) = @_;
 2637:     if ($dom eq '') {
 2638:         $dom = $env{'request.role.domain'};
 2639:     }
 2640:     my %can_assign = (
 2641:                           krb4 => 1,
 2642:                           krb5 => 1,
 2643:                           int  => 1,
 2644:                           loc  => 1,
 2645:                      );
 2646:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2647:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2648:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2649:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2650:             my $context;
 2651:             if ($env{'request.role'} =~ /^au/) {
 2652:                 $context = 'author';
 2653:             } elsif ($env{'request.role'} =~ /^dc/) {
 2654:                 $context = 'domain';
 2655:             } elsif ($env{'request.course.id'}) {
 2656:                 $context = 'course';
 2657:             }
 2658:             if ($context) {
 2659:                 if (ref($authhash->{$context}) eq 'HASH') {
 2660:                    %can_assign = %{$authhash->{$context}}; 
 2661:                 }
 2662:             }
 2663:         }
 2664:     }
 2665:     my $authnum = 0;
 2666:     foreach my $key (keys(%can_assign)) {
 2667:         if ($can_assign{$key}) {
 2668:             $authnum ++;
 2669:         }
 2670:     }
 2671:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2672:         $authnum --;
 2673:     }
 2674:     return ($authnum,%can_assign);
 2675: }
 2676: 
 2677: ###############################################################
 2678: ##    Get Kerberos Defaults for Domain                 ##
 2679: ###############################################################
 2680: ##
 2681: ## Returns default kerberos version and an associated argument
 2682: ## as listed in file domain.tab. If not listed, provides
 2683: ## appropriate default domain and kerberos version.
 2684: ##
 2685: #-------------------------------------------
 2686: 
 2687: =pod
 2688: 
 2689: =item * &get_kerberos_defaults()
 2690: 
 2691: get_kerberos_defaults($target_domain) returns the default kerberos
 2692: version and domain. If not found, it defaults to version 4 and the 
 2693: domain of the server.
 2694: 
 2695: =over 4
 2696: 
 2697: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2698: 
 2699: =back
 2700: 
 2701: =back
 2702: 
 2703: =cut
 2704: 
 2705: #-------------------------------------------
 2706: sub get_kerberos_defaults {
 2707:     my $domain=shift;
 2708:     my ($krbdef,$krbdefdom);
 2709:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2710:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2711:         $krbdef = $domdefaults{'auth_def'};
 2712:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2713:     } else {
 2714:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2715:         my $krbdefdom=$1;
 2716:         $krbdefdom=~tr/a-z/A-Z/;
 2717:         $krbdef = "krb4";
 2718:     }
 2719:     return ($krbdef,$krbdefdom);
 2720: }
 2721: 
 2722: 
 2723: ###############################################################
 2724: ##                Thesaurus Functions                        ##
 2725: ###############################################################
 2726: 
 2727: =pod
 2728: 
 2729: =head1 Thesaurus Functions
 2730: 
 2731: =over 4
 2732: 
 2733: =item * &initialize_keywords()
 2734: 
 2735: Initializes the package variable %Keywords if it is empty.  Uses the
 2736: package variable $thesaurus_db_file.
 2737: 
 2738: =cut
 2739: 
 2740: ###################################################
 2741: 
 2742: sub initialize_keywords {
 2743:     return 1 if (scalar keys(%Keywords));
 2744:     # If we are here, %Keywords is empty, so fill it up
 2745:     #   Make sure the file we need exists...
 2746:     if (! -e $thesaurus_db_file) {
 2747:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2748:                                  " failed because it does not exist");
 2749:         return 0;
 2750:     }
 2751:     #   Set up the hash as a database
 2752:     my %thesaurus_db;
 2753:     if (! tie(%thesaurus_db,'GDBM_File',
 2754:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2755:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2756:                                  $thesaurus_db_file);
 2757:         return 0;
 2758:     } 
 2759:     #  Get the average number of appearances of a word.
 2760:     my $avecount = $thesaurus_db{'average.count'};
 2761:     #  Put keywords (those that appear > average) into %Keywords
 2762:     while (my ($word,$data)=each (%thesaurus_db)) {
 2763:         my ($count,undef) = split /:/,$data;
 2764:         $Keywords{$word}++ if ($count > $avecount);
 2765:     }
 2766:     untie %thesaurus_db;
 2767:     # Remove special values from %Keywords.
 2768:     foreach my $value ('total.count','average.count') {
 2769:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2770:   }
 2771:     return 1;
 2772: }
 2773: 
 2774: ###################################################
 2775: 
 2776: =pod
 2777: 
 2778: =item * &keyword($word)
 2779: 
 2780: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2781: than the average number of times in the thesaurus database.  Calls 
 2782: &initialize_keywords
 2783: 
 2784: =cut
 2785: 
 2786: ###################################################
 2787: 
 2788: sub keyword {
 2789:     return if (!&initialize_keywords());
 2790:     my $word=lc(shift());
 2791:     $word=~s/\W//g;
 2792:     return exists($Keywords{$word});
 2793: }
 2794: 
 2795: ###############################################################
 2796: 
 2797: =pod 
 2798: 
 2799: =item * &get_related_words()
 2800: 
 2801: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2802: an array of words.  If the keyword is not in the thesaurus, an empty array
 2803: will be returned.  The order of the words returned is determined by the
 2804: database which holds them.
 2805: 
 2806: Uses global $thesaurus_db_file.
 2807: 
 2808: =cut
 2809: 
 2810: ###############################################################
 2811: sub get_related_words {
 2812:     my $keyword = shift;
 2813:     my %thesaurus_db;
 2814:     if (! -e $thesaurus_db_file) {
 2815:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2816:                                  "failed because the file does not exist");
 2817:         return ();
 2818:     }
 2819:     if (! tie(%thesaurus_db,'GDBM_File',
 2820:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2821:         return ();
 2822:     } 
 2823:     my @Words=();
 2824:     my $count=0;
 2825:     if (exists($thesaurus_db{$keyword})) {
 2826: 	# The first element is the number of times
 2827: 	# the word appears.  We do not need it now.
 2828: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2829: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2830: 	my $threshold=$mostfrequentcount/10;
 2831:         foreach my $possibleword (@RelatedWords) {
 2832:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2833:             if ($wordcount>$threshold) {
 2834: 		push(@Words,$word);
 2835:                 $count++;
 2836:                 if ($count>10) { last; }
 2837: 	    }
 2838:         }
 2839:     }
 2840:     untie %thesaurus_db;
 2841:     return @Words;
 2842: }
 2843: 
 2844: =pod
 2845: 
 2846: =back
 2847: 
 2848: =cut
 2849: 
 2850: # -------------------------------------------------------------- Plaintext name
 2851: =pod
 2852: 
 2853: =head1 User Name Functions
 2854: 
 2855: =over 4
 2856: 
 2857: =item * &plainname($uname,$udom,$first)
 2858: 
 2859: Takes a users logon name and returns it as a string in
 2860: "first middle last generation" form 
 2861: if $first is set to 'lastname' then it returns it as
 2862: 'lastname generation, firstname middlename' if their is a lastname
 2863: 
 2864: =cut
 2865: 
 2866: 
 2867: ###############################################################
 2868: sub plainname {
 2869:     my ($uname,$udom,$first)=@_;
 2870:     return if (!defined($uname) || !defined($udom));
 2871:     my %names=&getnames($uname,$udom);
 2872:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2873: 					  $names{'middlename'},
 2874: 					  $names{'lastname'},
 2875: 					  $names{'generation'},$first);
 2876:     $name=~s/^\s+//;
 2877:     $name=~s/\s+$//;
 2878:     $name=~s/\s+/ /g;
 2879:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2880:     return $name;
 2881: }
 2882: 
 2883: # -------------------------------------------------------------------- Nickname
 2884: =pod
 2885: 
 2886: =item * &nickname($uname,$udom)
 2887: 
 2888: Gets a users name and returns it as a string as
 2889: 
 2890: "&quot;nickname&quot;"
 2891: 
 2892: if the user has a nickname or
 2893: 
 2894: "first middle last generation"
 2895: 
 2896: if the user does not
 2897: 
 2898: =cut
 2899: 
 2900: sub nickname {
 2901:     my ($uname,$udom)=@_;
 2902:     return if (!defined($uname) || !defined($udom));
 2903:     my %names=&getnames($uname,$udom);
 2904:     my $name=$names{'nickname'};
 2905:     if ($name) {
 2906:        $name='&quot;'.$name.'&quot;'; 
 2907:     } else {
 2908:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2909: 	     $names{'lastname'}.' '.$names{'generation'};
 2910:        $name=~s/\s+$//;
 2911:        $name=~s/\s+/ /g;
 2912:     }
 2913:     return $name;
 2914: }
 2915: 
 2916: sub getnames {
 2917:     my ($uname,$udom)=@_;
 2918:     return if (!defined($uname) || !defined($udom));
 2919:     if ($udom eq 'public' && $uname eq 'public') {
 2920: 	return ('lastname' => &mt('Public'));
 2921:     }
 2922:     my $id=$uname.':'.$udom;
 2923:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2924:     if ($cached) {
 2925: 	return %{$names};
 2926:     } else {
 2927: 	my %loadnames=&Apache::lonnet::get('environment',
 2928:                     ['firstname','middlename','lastname','generation','nickname'],
 2929: 					 $udom,$uname);
 2930: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2931: 	return %loadnames;
 2932:     }
 2933: }
 2934: 
 2935: # -------------------------------------------------------------------- getemails
 2936: 
 2937: =pod
 2938: 
 2939: =item * &getemails($uname,$udom)
 2940: 
 2941: Gets a user's email information and returns it as a hash with keys:
 2942: notification, critnotification, permanentemail
 2943: 
 2944: For notification and critnotification, values are comma-separated lists 
 2945: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2946:  
 2947: 
 2948: =cut
 2949: 
 2950: 
 2951: sub getemails {
 2952:     my ($uname,$udom)=@_;
 2953:     if ($udom eq 'public' && $uname eq 'public') {
 2954: 	return;
 2955:     }
 2956:     if (!$udom) { $udom=$env{'user.domain'}; }
 2957:     if (!$uname) { $uname=$env{'user.name'}; }
 2958:     my $id=$uname.':'.$udom;
 2959:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2960:     if ($cached) {
 2961: 	return %{$names};
 2962:     } else {
 2963: 	my %loadnames=&Apache::lonnet::get('environment',
 2964:                     			   ['notification','critnotification',
 2965: 					    'permanentemail'],
 2966: 					   $udom,$uname);
 2967: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2968: 	return %loadnames;
 2969:     }
 2970: }
 2971: 
 2972: sub flush_email_cache {
 2973:     my ($uname,$udom)=@_;
 2974:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2975:     if (!$uname) { $uname=$env{'user.name'};   }
 2976:     return if ($udom eq 'public' && $uname eq 'public');
 2977:     my $id=$uname.':'.$udom;
 2978:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2979: }
 2980: 
 2981: # -------------------------------------------------------------------- getlangs
 2982: 
 2983: =pod
 2984: 
 2985: =item * &getlangs($uname,$udom)
 2986: 
 2987: Gets a user's language preference and returns it as a hash with key:
 2988: language.
 2989: 
 2990: =cut
 2991: 
 2992: 
 2993: sub getlangs {
 2994:     my ($uname,$udom) = @_;
 2995:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2996:     if (!$uname) { $uname=$env{'user.name'};   }
 2997:     my $id=$uname.':'.$udom;
 2998:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2999:     if ($cached) {
 3000:         return %{$langs};
 3001:     } else {
 3002:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3003:                                            $udom,$uname);
 3004:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3005:         return %loadlangs;
 3006:     }
 3007: }
 3008: 
 3009: sub flush_langs_cache {
 3010:     my ($uname,$udom)=@_;
 3011:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3012:     if (!$uname) { $uname=$env{'user.name'};   }
 3013:     return if ($udom eq 'public' && $uname eq 'public');
 3014:     my $id=$uname.':'.$udom;
 3015:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3016: }
 3017: 
 3018: # ------------------------------------------------------------------ Screenname
 3019: 
 3020: =pod
 3021: 
 3022: =item * &screenname($uname,$udom)
 3023: 
 3024: Gets a users screenname and returns it as a string
 3025: 
 3026: =cut
 3027: 
 3028: sub screenname {
 3029:     my ($uname,$udom)=@_;
 3030:     if ($uname eq $env{'user.name'} &&
 3031: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3032:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3033:     return $names{'screenname'};
 3034: }
 3035: 
 3036: 
 3037: # ------------------------------------------------------------- Confirm Wrapper
 3038: =pod
 3039: 
 3040: =item confirmwrapper
 3041: 
 3042: Wrap messages about completion of operation in box
 3043: 
 3044: =cut
 3045: 
 3046: sub confirmwrapper {
 3047:     my ($message)=@_;
 3048:     if ($message) {
 3049:         return "\n".'<div class="LC_confirm_box">'."\n"
 3050:                .$message."\n"
 3051:                .'</div>'."\n";
 3052:     } else {
 3053:         return $message;
 3054:     }
 3055: }
 3056: 
 3057: # ------------------------------------------------------------- Message Wrapper
 3058: 
 3059: sub messagewrapper {
 3060:     my ($link,$username,$domain,$subject,$text)=@_;
 3061:     return 
 3062:         '<a href="/adm/email?compose=individual&amp;'.
 3063:         'recname='.$username.'&amp;recdom='.$domain.
 3064: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3065:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3066: }
 3067: 
 3068: # --------------------------------------------------------------- Notes Wrapper
 3069: 
 3070: sub noteswrapper {
 3071:     my ($link,$un,$do)=@_;
 3072:     return 
 3073: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3074: }
 3075: 
 3076: # ------------------------------------------------------------- Aboutme Wrapper
 3077: 
 3078: sub aboutmewrapper {
 3079:     my ($link,$username,$domain,$target)=@_;
 3080:     if (!defined($username)  && !defined($domain)) {
 3081:         return;
 3082:     }
 3083:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3084: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3085: }
 3086: 
 3087: # ------------------------------------------------------------ Syllabus Wrapper
 3088: 
 3089: sub syllabuswrapper {
 3090:     my ($linktext,$coursedir,$domain)=@_;
 3091:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3092: }
 3093: 
 3094: # -----------------------------------------------------------------------------
 3095: 
 3096: sub track_student_link {
 3097:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3098:     my $link ="/adm/trackstudent?";
 3099:     my $title = 'View recent activity';
 3100:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3101:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3102:         $link .= "selected_student=$sname:$sdom";
 3103:         $title .= ' of this student';
 3104:     } 
 3105:     if (defined($target) && $target !~ /^\s*$/) {
 3106:         $target = qq{target="$target"};
 3107:     } else {
 3108:         $target = '';
 3109:     }
 3110:     if ($start) { $link.='&amp;start='.$start; }
 3111:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3112:     $title = &mt($title);
 3113:     $linktext = &mt($linktext);
 3114:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3115: 	&help_open_topic('View_recent_activity');
 3116: }
 3117: 
 3118: sub slot_reservations_link {
 3119:     my ($linktext,$sname,$sdom,$target) = @_;
 3120:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3121:     my $title = 'View slot reservation history';
 3122:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3123:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3124:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3125:         $title .= ' of this student';
 3126:     }
 3127:     if (defined($target) && $target !~ /^\s*$/) {
 3128:         $target = qq{target="$target"};
 3129:     } else {
 3130:         $target = '';
 3131:     }
 3132:     $title = &mt($title);
 3133:     $linktext = &mt($linktext);
 3134:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3135: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3136: 
 3137: }
 3138: 
 3139: # ===================================================== Display a student photo
 3140: 
 3141: 
 3142: sub student_image_tag {
 3143:     my ($domain,$user)=@_;
 3144:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3145:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3146: 	return '<img src="'.$imgsrc.'" align="right" />';
 3147:     } else {
 3148: 	return '';
 3149:     }
 3150: }
 3151: 
 3152: =pod
 3153: 
 3154: =back
 3155: 
 3156: =head1 Access .tab File Data
 3157: 
 3158: =over 4
 3159: 
 3160: =item * &languageids() 
 3161: 
 3162: returns list of all language ids
 3163: 
 3164: =cut
 3165: 
 3166: sub languageids {
 3167:     return sort(keys(%language));
 3168: }
 3169: 
 3170: =pod
 3171: 
 3172: =item * &languagedescription() 
 3173: 
 3174: returns description of a specified language id
 3175: 
 3176: =cut
 3177: 
 3178: sub languagedescription {
 3179:     my $code=shift;
 3180:     return  ($supported_language{$code}?'* ':'').
 3181:             $language{$code}.
 3182: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3183: }
 3184: 
 3185: sub plainlanguagedescription {
 3186:     my $code=shift;
 3187:     return $language{$code};
 3188: }
 3189: 
 3190: sub supportedlanguagecode {
 3191:     my $code=shift;
 3192:     return $supported_language{$code};
 3193: }
 3194: 
 3195: =pod
 3196: 
 3197: =item * &copyrightids() 
 3198: 
 3199: returns list of all copyrights
 3200: 
 3201: =cut
 3202: 
 3203: sub copyrightids {
 3204:     return sort(keys(%cprtag));
 3205: }
 3206: 
 3207: =pod
 3208: 
 3209: =item * &copyrightdescription() 
 3210: 
 3211: returns description of a specified copyright id
 3212: 
 3213: =cut
 3214: 
 3215: sub copyrightdescription {
 3216:     return &mt($cprtag{shift(@_)});
 3217: }
 3218: 
 3219: =pod
 3220: 
 3221: =item * &source_copyrightids() 
 3222: 
 3223: returns list of all source copyrights
 3224: 
 3225: =cut
 3226: 
 3227: sub source_copyrightids {
 3228:     return sort(keys(%scprtag));
 3229: }
 3230: 
 3231: =pod
 3232: 
 3233: =item * &source_copyrightdescription() 
 3234: 
 3235: returns description of a specified source copyright id
 3236: 
 3237: =cut
 3238: 
 3239: sub source_copyrightdescription {
 3240:     return &mt($scprtag{shift(@_)});
 3241: }
 3242: 
 3243: =pod
 3244: 
 3245: =item * &filecategories() 
 3246: 
 3247: returns list of all file categories
 3248: 
 3249: =cut
 3250: 
 3251: sub filecategories {
 3252:     return sort(keys(%category_extensions));
 3253: }
 3254: 
 3255: =pod
 3256: 
 3257: =item * &filecategorytypes() 
 3258: 
 3259: returns list of file types belonging to a given file
 3260: category
 3261: 
 3262: =cut
 3263: 
 3264: sub filecategorytypes {
 3265:     my ($cat) = @_;
 3266:     return @{$category_extensions{lc($cat)}};
 3267: }
 3268: 
 3269: =pod
 3270: 
 3271: =item * &fileembstyle() 
 3272: 
 3273: returns embedding style for a specified file type
 3274: 
 3275: =cut
 3276: 
 3277: sub fileembstyle {
 3278:     return $fe{lc(shift(@_))};
 3279: }
 3280: 
 3281: sub filemimetype {
 3282:     return $fm{lc(shift(@_))};
 3283: }
 3284: 
 3285: 
 3286: sub filecategoryselect {
 3287:     my ($name,$value)=@_;
 3288:     return &select_form($value,$name,
 3289:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3290: }
 3291: 
 3292: =pod
 3293: 
 3294: =item * &filedescription() 
 3295: 
 3296: returns description for a specified file type
 3297: 
 3298: =cut
 3299: 
 3300: sub filedescription {
 3301:     my $file_description = $fd{lc(shift())};
 3302:     $file_description =~ s:([\[\]]):~$1:g;
 3303:     return &mt($file_description);
 3304: }
 3305: 
 3306: =pod
 3307: 
 3308: =item * &filedescriptionex() 
 3309: 
 3310: returns description for a specified file type with
 3311: extra formatting
 3312: 
 3313: =cut
 3314: 
 3315: sub filedescriptionex {
 3316:     my $ex=shift;
 3317:     my $file_description = $fd{lc($ex)};
 3318:     $file_description =~ s:([\[\]]):~$1:g;
 3319:     return '.'.$ex.' '.&mt($file_description);
 3320: }
 3321: 
 3322: # End of .tab access
 3323: =pod
 3324: 
 3325: =back
 3326: 
 3327: =cut
 3328: 
 3329: # ------------------------------------------------------------------ File Types
 3330: sub fileextensions {
 3331:     return sort(keys(%fe));
 3332: }
 3333: 
 3334: # ----------------------------------------------------------- Display Languages
 3335: # returns a hash with all desired display languages
 3336: #
 3337: 
 3338: sub display_languages {
 3339:     my %languages=();
 3340:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3341: 	$languages{$lang}=1;
 3342:     }
 3343:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3344:     if ($env{'form.displaylanguage'}) {
 3345: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3346: 	    $languages{$lang}=1;
 3347:         }
 3348:     }
 3349:     return %languages;
 3350: }
 3351: 
 3352: sub languages {
 3353:     my ($possible_langs) = @_;
 3354:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3355:     if (!ref($possible_langs)) {
 3356: 	if( wantarray ) {
 3357: 	    return @preferred_langs;
 3358: 	} else {
 3359: 	    return $preferred_langs[0];
 3360: 	}
 3361:     }
 3362:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3363:     my @preferred_possibilities;
 3364:     foreach my $preferred_lang (@preferred_langs) {
 3365: 	if (exists($possibilities{$preferred_lang})) {
 3366: 	    push(@preferred_possibilities, $preferred_lang);
 3367: 	}
 3368:     }
 3369:     if( wantarray ) {
 3370: 	return @preferred_possibilities;
 3371:     }
 3372:     return $preferred_possibilities[0];
 3373: }
 3374: 
 3375: sub user_lang {
 3376:     my ($touname,$toudom,$fromcid) = @_;
 3377:     my @userlangs;
 3378:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3379:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3380:                     $env{'course.'.$fromcid.'.languages'}));
 3381:     } else {
 3382:         my %langhash = &getlangs($touname,$toudom);
 3383:         if ($langhash{'languages'} ne '') {
 3384:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3385:         } else {
 3386:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3387:             if ($domdefs{'lang_def'} ne '') {
 3388:                 @userlangs = ($domdefs{'lang_def'});
 3389:             }
 3390:         }
 3391:     }
 3392:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3393:     my $user_lh = Apache::localize->get_handle(@languages);
 3394:     return $user_lh;
 3395: }
 3396: 
 3397: 
 3398: ###############################################################
 3399: ##               Student Answer Attempts                     ##
 3400: ###############################################################
 3401: 
 3402: =pod
 3403: 
 3404: =head1 Alternate Problem Views
 3405: 
 3406: =over 4
 3407: 
 3408: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3409:     $getattempt, $regexp, $gradesub)
 3410: 
 3411: Return string with previous attempt on problem. Arguments:
 3412: 
 3413: =over 4
 3414: 
 3415: =item * $symb: Problem, including path
 3416: 
 3417: =item * $username: username of the desired student
 3418: 
 3419: =item * $domain: domain of the desired student
 3420: 
 3421: =item * $course: Course ID
 3422: 
 3423: =item * $getattempt: Leave blank for all attempts, otherwise put
 3424:     something
 3425: 
 3426: =item * $regexp: if string matches this regexp, the string will be
 3427:     sent to $gradesub
 3428: 
 3429: =item * $gradesub: routine that processes the string if it matches $regexp
 3430: 
 3431: =back
 3432: 
 3433: The output string is a table containing all desired attempts, if any.
 3434: 
 3435: =cut
 3436: 
 3437: sub get_previous_attempt {
 3438:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3439:   my $prevattempts='';
 3440:   no strict 'refs';
 3441:   if ($symb) {
 3442:     my (%returnhash)=
 3443:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3444:     if ($returnhash{'version'}) {
 3445:       my %lasthash=();
 3446:       my $version;
 3447:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3448:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3449: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3450:         }
 3451:       }
 3452:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3453:       $prevattempts.='<th>'.&mt('History').'</th>';
 3454:       my (%typeparts,%lasthidden);
 3455:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3456:       foreach my $key (sort(keys(%lasthash))) {
 3457: 	my ($ign,@parts) = split(/\./,$key);
 3458: 	if ($#parts > 0) {
 3459: 	  my $data=$parts[-1];
 3460:           next if ($data eq 'foilorder');
 3461: 	  pop(@parts);
 3462:           if ($data eq 'type') {
 3463:               unless ($showsurv) {
 3464:                   my $id = join(',',@parts);
 3465:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3466:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3467:                       $lasthidden{$ign.'.'.$id} = 1;
 3468:                   }
 3469:               }
 3470:               delete($lasthash{$key});
 3471:           } else {
 3472: 	      $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3473:           }
 3474: 	} else {
 3475: 	  if ($#parts == 0) {
 3476: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3477: 	  } else {
 3478: 	    $prevattempts.='<th>'.$ign.'</th>';
 3479: 	  }
 3480: 	}
 3481:       }
 3482:       $prevattempts.=&end_data_table_header_row();
 3483:       if ($getattempt eq '') {
 3484: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3485:             my @hidden;
 3486:             if (%typeparts) {
 3487:                 foreach my $id (keys(%typeparts)) {
 3488:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3489:                         push(@hidden,$id);
 3490:                     }
 3491:                 }
 3492:             }
 3493:             $prevattempts.=&start_data_table_row().
 3494:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3495:             if (@hidden) {
 3496:                 foreach my $key (sort(keys(%lasthash))) {
 3497:                     next if ($key =~ /\.foilorder$/);
 3498:                     my $hide;
 3499:                     foreach my $id (@hidden) {
 3500:                         if ($key =~ /^\Q$id\E/) {
 3501:                             $hide = 1;
 3502:                             last;
 3503:                         }
 3504:                     }
 3505:                     if ($hide) {
 3506:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3507:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3508:                             my $value = &format_previous_attempt_value($key,
 3509:                                              $returnhash{$version.':'.$key});
 3510:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3511:                         } else {
 3512:                             $prevattempts.='<td>&nbsp;</td>';
 3513:                         }
 3514:                     } else {
 3515:                         if ($key =~ /\./) {
 3516:                             my $value = &format_previous_attempt_value($key,
 3517:                                               $returnhash{$version.':'.$key});
 3518:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3519:                         } else {
 3520:                             $prevattempts.='<td>&nbsp;</td>';
 3521:                         }
 3522:                     }
 3523:                 }
 3524:             } else {
 3525: 	        foreach my $key (sort(keys(%lasthash))) {
 3526:                     next if ($key =~ /\.foilorder$/);
 3527: 		    my $value = &format_previous_attempt_value($key,
 3528: 			            $returnhash{$version.':'.$key});
 3529: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3530: 	        }
 3531:             }
 3532: 	    $prevattempts.=&end_data_table_row();
 3533: 	 }
 3534:       }
 3535:       my @currhidden = keys(%lasthidden);
 3536:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3537:       foreach my $key (sort(keys(%lasthash))) {
 3538:           next if ($key =~ /\.foilorder$/);
 3539:           if (%typeparts) {
 3540:               my $hidden;
 3541:               foreach my $id (@currhidden) {
 3542:                   if ($key =~ /^\Q$id\E/) {
 3543:                       $hidden = 1;
 3544:                       last;
 3545:                   }
 3546:               }
 3547:               if ($hidden) {
 3548:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3549:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3550:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3551:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3552:                           $value = &$gradesub($value);
 3553:                       }
 3554:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3555:                   } else {
 3556:                       $prevattempts.='<td>&nbsp;</td>';
 3557:                   }
 3558:               } else {
 3559:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3560:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3561:                       $value = &$gradesub($value);
 3562:                   }
 3563:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3564:               }
 3565:           } else {
 3566: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3567: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3568:                   $value = &$gradesub($value);
 3569:               }
 3570: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3571:           }
 3572:       }
 3573:       $prevattempts.= &end_data_table_row().&end_data_table();
 3574:     } else {
 3575:       $prevattempts=
 3576: 	  &start_data_table().&start_data_table_row().
 3577: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3578: 	  &end_data_table_row().&end_data_table();
 3579:     }
 3580:   } else {
 3581:     $prevattempts=
 3582: 	  &start_data_table().&start_data_table_row().
 3583: 	  '<td>'.&mt('No data.').'</td>'.
 3584: 	  &end_data_table_row().&end_data_table();
 3585:   }
 3586: }
 3587: 
 3588: sub format_previous_attempt_value {
 3589:     my ($key,$value) = @_;
 3590:     if ($key =~ /timestamp/) {
 3591: 	$value = &Apache::lonlocal::locallocaltime($value);
 3592:     } elsif (ref($value) eq 'ARRAY') {
 3593: 	$value = '('.join(', ', @{ $value }).')';
 3594:     } elsif ($key =~ /answerstring$/) {
 3595:         my %answers = &Apache::lonnet::str2hash($value);
 3596:         my @anskeys = sort(keys(%answers));
 3597:         if (@anskeys == 1) {
 3598:             my $answer = $answers{$anskeys[0]};
 3599:             if ($answer =~ m{\0}) {
 3600:                 $answer =~ s{\0}{,}g;
 3601:             }
 3602:             my $tag_internal_answer_name = 'INTERNAL';
 3603:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3604:                 $value = $answer; 
 3605:             } else {
 3606:                 $value = $anskeys[0].'='.$answer;
 3607:             }
 3608:         } else {
 3609:             foreach my $ans (@anskeys) {
 3610:                 my $answer = $answers{$ans};
 3611:                 if ($answer =~ m{\0}) {
 3612:                     $answer =~ s{\0}{,}g;
 3613:                 }
 3614:                 $value .=  $ans.'='.$answer.'<br />';;
 3615:             } 
 3616:         }
 3617:     } else {
 3618: 	$value = &unescape($value);
 3619:     }
 3620:     return $value;
 3621: }
 3622: 
 3623: 
 3624: sub relative_to_absolute {
 3625:     my ($url,$output)=@_;
 3626:     my $parser=HTML::TokeParser->new(\$output);
 3627:     my $token;
 3628:     my $thisdir=$url;
 3629:     my @rlinks=();
 3630:     while ($token=$parser->get_token) {
 3631: 	if ($token->[0] eq 'S') {
 3632: 	    if ($token->[1] eq 'a') {
 3633: 		if ($token->[2]->{'href'}) {
 3634: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3635: 		}
 3636: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3637: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3638: 	    } elsif ($token->[1] eq 'base') {
 3639: 		$thisdir=$token->[2]->{'href'};
 3640: 	    }
 3641: 	}
 3642:     }
 3643:     $thisdir=~s-/[^/]*$--;
 3644:     foreach my $link (@rlinks) {
 3645: 	unless (($link=~/^https?\:\/\//i) ||
 3646: 		($link=~/^\//) ||
 3647: 		($link=~/^javascript:/i) ||
 3648: 		($link=~/^mailto:/i) ||
 3649: 		($link=~/^\#/)) {
 3650: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3651: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3652: 	}
 3653:     }
 3654: # -------------------------------------------------- Deal with Applet codebases
 3655:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3656:     return $output;
 3657: }
 3658: 
 3659: =pod
 3660: 
 3661: =item * &get_student_view()
 3662: 
 3663: show a snapshot of what student was looking at
 3664: 
 3665: =cut
 3666: 
 3667: sub get_student_view {
 3668:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3669:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3670:   my (%form);
 3671:   my @elements=('symb','courseid','domain','username');
 3672:   foreach my $element (@elements) {
 3673:       $form{'grade_'.$element}=eval '$'.$element #'
 3674:   }
 3675:   if (defined($moreenv)) {
 3676:       %form=(%form,%{$moreenv});
 3677:   }
 3678:   if (defined($target)) { $form{'grade_target'} = $target; }
 3679:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3680:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3681:   $userview=~s/\<body[^\>]*\>//gi;
 3682:   $userview=~s/\<\/body\>//gi;
 3683:   $userview=~s/\<html\>//gi;
 3684:   $userview=~s/\<\/html\>//gi;
 3685:   $userview=~s/\<head\>//gi;
 3686:   $userview=~s/\<\/head\>//gi;
 3687:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3688:   $userview=&relative_to_absolute($feedurl,$userview);
 3689:   if (wantarray) {
 3690:      return ($userview,$response);
 3691:   } else {
 3692:      return $userview;
 3693:   }
 3694: }
 3695: 
 3696: sub get_student_view_with_retries {
 3697:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3698: 
 3699:     my $ok = 0;                 # True if we got a good response.
 3700:     my $content;
 3701:     my $response;
 3702: 
 3703:     # Try to get the student_view done. within the retries count:
 3704:     
 3705:     do {
 3706:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3707:          $ok      = $response->is_success;
 3708:          if (!$ok) {
 3709:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3710:          }
 3711:          $retries--;
 3712:     } while (!$ok && ($retries > 0));
 3713:     
 3714:     if (!$ok) {
 3715:        $content = '';          # On error return an empty content.
 3716:     }
 3717:     if (wantarray) {
 3718:        return ($content, $response);
 3719:     } else {
 3720:        return $content;
 3721:     }
 3722: }
 3723: 
 3724: =pod
 3725: 
 3726: =item * &get_student_answers() 
 3727: 
 3728: show a snapshot of how student was answering problem
 3729: 
 3730: =cut
 3731: 
 3732: sub get_student_answers {
 3733:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3734:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3735:   my (%moreenv);
 3736:   my @elements=('symb','courseid','domain','username');
 3737:   foreach my $element (@elements) {
 3738:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3739:   }
 3740:   $moreenv{'grade_target'}='answer';
 3741:   %moreenv=(%form,%moreenv);
 3742:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3743:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3744:   return $userview;
 3745: }
 3746: 
 3747: =pod
 3748: 
 3749: =item * &submlink()
 3750: 
 3751: Inputs: $text $uname $udom $symb $target
 3752: 
 3753: Returns: A link to grades.pm such as to see the SUBM view of a student
 3754: 
 3755: =cut
 3756: 
 3757: ###############################################
 3758: sub submlink {
 3759:     my ($text,$uname,$udom,$symb,$target)=@_;
 3760:     if (!($uname && $udom)) {
 3761: 	(my $cursymb, my $courseid,$udom,$uname)=
 3762: 	    &Apache::lonnet::whichuser($symb);
 3763: 	if (!$symb) { $symb=$cursymb; }
 3764:     }
 3765:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3766:     $symb=&escape($symb);
 3767:     if ($target) { $target=" target=\"$target\""; }
 3768:     return
 3769:         '<a href="/adm/grades?command=submission'.
 3770:         '&amp;symb='.$symb.
 3771:         '&amp;student='.$uname.
 3772:         '&amp;userdom='.$udom.'"'.
 3773:         $target.'>'.$text.'</a>';
 3774: }
 3775: ##############################################
 3776: 
 3777: =pod
 3778: 
 3779: =item * &pgrdlink()
 3780: 
 3781: Inputs: $text $uname $udom $symb $target
 3782: 
 3783: Returns: A link to grades.pm such as to see the PGRD view of a student
 3784: 
 3785: =cut
 3786: 
 3787: ###############################################
 3788: sub pgrdlink {
 3789:     my $link=&submlink(@_);
 3790:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3791:     return $link;
 3792: }
 3793: ##############################################
 3794: 
 3795: =pod
 3796: 
 3797: =item * &pprmlink()
 3798: 
 3799: Inputs: $text $uname $udom $symb $target
 3800: 
 3801: Returns: A link to parmset.pm such as to see the PPRM view of a
 3802: student and a specific resource
 3803: 
 3804: =cut
 3805: 
 3806: ###############################################
 3807: sub pprmlink {
 3808:     my ($text,$uname,$udom,$symb,$target)=@_;
 3809:     if (!($uname && $udom)) {
 3810: 	(my $cursymb, my $courseid,$udom,$uname)=
 3811: 	    &Apache::lonnet::whichuser($symb);
 3812: 	if (!$symb) { $symb=$cursymb; }
 3813:     }
 3814:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3815:     $symb=&escape($symb);
 3816:     if ($target) { $target="target=\"$target\""; }
 3817:     return '<a href="/adm/parmset?command=set&amp;'.
 3818: 	'symb='.$symb.'&amp;uname='.$uname.
 3819: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3820: }
 3821: ##############################################
 3822: 
 3823: =pod
 3824: 
 3825: =back
 3826: 
 3827: =cut
 3828: 
 3829: ###############################################
 3830: 
 3831: 
 3832: sub timehash {
 3833:     my ($thistime) = @_;
 3834:     my $timezone = &Apache::lonlocal::gettimezone();
 3835:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3836:                      ->set_time_zone($timezone);
 3837:     my $wday = $dt->day_of_week();
 3838:     if ($wday == 7) { $wday = 0; }
 3839:     return ( 'second' => $dt->second(),
 3840:              'minute' => $dt->minute(),
 3841:              'hour'   => $dt->hour(),
 3842:              'day'     => $dt->day_of_month(),
 3843:              'month'   => $dt->month(),
 3844:              'year'    => $dt->year(),
 3845:              'weekday' => $wday,
 3846:              'dayyear' => $dt->day_of_year(),
 3847:              'dlsav'   => $dt->is_dst() );
 3848: }
 3849: 
 3850: sub utc_string {
 3851:     my ($date)=@_;
 3852:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3853: }
 3854: 
 3855: sub maketime {
 3856:     my %th=@_;
 3857:     my ($epoch_time,$timezone,$dt);
 3858:     $timezone = &Apache::lonlocal::gettimezone();
 3859:     eval {
 3860:         $dt = DateTime->new( year   => $th{'year'},
 3861:                              month  => $th{'month'},
 3862:                              day    => $th{'day'},
 3863:                              hour   => $th{'hour'},
 3864:                              minute => $th{'minute'},
 3865:                              second => $th{'second'},
 3866:                              time_zone => $timezone,
 3867:                          );
 3868:     };
 3869:     if (!$@) {
 3870:         $epoch_time = $dt->epoch;
 3871:         if ($epoch_time) {
 3872:             return $epoch_time;
 3873:         }
 3874:     }
 3875:     return POSIX::mktime(
 3876:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3877:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3878: }
 3879: 
 3880: #########################################
 3881: 
 3882: sub findallcourses {
 3883:     my ($roles,$uname,$udom) = @_;
 3884:     my %roles;
 3885:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3886:     my %courses;
 3887:     my $now=time;
 3888:     if (!defined($uname)) {
 3889:         $uname = $env{'user.name'};
 3890:     }
 3891:     if (!defined($udom)) {
 3892:         $udom = $env{'user.domain'};
 3893:     }
 3894:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3895:         my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 3896:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
 3897:                                               $extra);
 3898:         if (!%roles) {
 3899:             %roles = (
 3900:                        cc => 1,
 3901:                        co => 1,
 3902:                        in => 1,
 3903:                        ep => 1,
 3904:                        ta => 1,
 3905:                        cr => 1,
 3906:                        st => 1,
 3907:              );
 3908:         }
 3909:         foreach my $entry (keys(%roleshash)) {
 3910:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3911:             if ($trole =~ /^cr/) { 
 3912:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3913:             } else {
 3914:                 next if (!exists($roles{$trole}));
 3915:             }
 3916:             if ($tend) {
 3917:                 next if ($tend < $now);
 3918:             }
 3919:             if ($tstart) {
 3920:                 next if ($tstart > $now);
 3921:             }
 3922:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3923:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3924:             if ($secpart eq '') {
 3925:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3926:                 $sec = 'none';
 3927:                 $realsec = '';
 3928:             } else {
 3929:                 $cnum = $cnumpart;
 3930:                 ($sec,$role) = split(/_/,$secpart);
 3931:                 $realsec = $sec;
 3932:             }
 3933:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3934:         }
 3935:     } else {
 3936:         foreach my $key (keys(%env)) {
 3937: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3938:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3939: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3940: 	        next if ($role eq 'ca' || $role eq 'aa');
 3941: 	        next if (%roles && !exists($roles{$role}));
 3942: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3943:                 my $active=1;
 3944:                 if ($starttime) {
 3945: 		    if ($now<$starttime) { $active=0; }
 3946:                 }
 3947:                 if ($endtime) {
 3948:                     if ($now>$endtime) { $active=0; }
 3949:                 }
 3950:                 if ($active) {
 3951:                     if ($sec eq '') {
 3952:                         $sec = 'none';
 3953:                     }
 3954:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3955:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3956:                 }
 3957:             }
 3958:         }
 3959:     }
 3960:     return %courses;
 3961: }
 3962: 
 3963: ###############################################
 3964: 
 3965: sub blockcheck {
 3966:     my ($setters,$activity,$uname,$udom) = @_;
 3967: 
 3968:     if (!defined($udom)) {
 3969:         $udom = $env{'user.domain'};
 3970:     }
 3971:     if (!defined($uname)) {
 3972:         $uname = $env{'user.name'};
 3973:     }
 3974: 
 3975:     # If uname and udom are for a course, check for blocks in the course.
 3976: 
 3977:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3978:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3979:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3980:         return ($startblock,$endblock);
 3981:     }
 3982: 
 3983:     my $startblock = 0;
 3984:     my $endblock = 0;
 3985:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3986: 
 3987:     # If uname is for a user, and activity is course-specific, i.e.,
 3988:     # boards, chat or groups, check for blocking in current course only.
 3989: 
 3990:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3991:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3992:         foreach my $key (keys(%live_courses)) {
 3993:             if ($key ne $env{'request.course.id'}) {
 3994:                 delete($live_courses{$key});
 3995:             }
 3996:         }
 3997:     }
 3998: 
 3999:     my $otheruser = 0;
 4000:     my %own_courses;
 4001:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4002:         # Resource belongs to user other than current user.
 4003:         $otheruser = 1;
 4004:         # Gather courses for current user
 4005:         %own_courses = 
 4006:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4007:     }
 4008: 
 4009:     # Gather active course roles - course coordinator, instructor, 
 4010:     # exam proctor, ta, student, or custom role.
 4011: 
 4012:     foreach my $course (keys(%live_courses)) {
 4013:         my ($cdom,$cnum);
 4014:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4015:             $cdom = $env{'course.'.$course.'.domain'};
 4016:             $cnum = $env{'course.'.$course.'.num'};
 4017:         } else {
 4018:             ($cdom,$cnum) = split(/_/,$course); 
 4019:         }
 4020:         my $no_ownblock = 0;
 4021:         my $no_userblock = 0;
 4022:         if ($otheruser && $activity ne 'com') {
 4023:             # Check if current user has 'evb' priv for this
 4024:             if (defined($own_courses{$course})) {
 4025:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4026:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4027:                     if ($sec ne 'none') {
 4028:                         $checkrole .= '/'.$sec;
 4029:                     }
 4030:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4031:                         $no_ownblock = 1;
 4032:                         last;
 4033:                     }
 4034:                 }
 4035:             }
 4036:             # if they have 'evb' priv and are currently not playing student
 4037:             next if (($no_ownblock) &&
 4038:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4039:         }
 4040:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4041:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4042:             if ($sec ne 'none') {
 4043:                 $checkrole .= '/'.$sec;
 4044:             }
 4045:             if ($otheruser) {
 4046:                 # Resource belongs to user other than current user.
 4047:                 # Assemble privs for that user, and check for 'evb' priv.
 4048:                 my ($trole,$tdom,$tnum,$tsec);
 4049:                 my $entry = $live_courses{$course}{$sec};
 4050:                 if ($entry =~ /^cr/) {
 4051:                     ($trole,$tdom,$tnum,$tsec) = 
 4052:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4053:                 } else {
 4054:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4055:                 }
 4056:                 my ($spec,$area,$trest,%allroles,%userroles);
 4057:                 $area = '/'.$tdom.'/'.$tnum;
 4058:                 $trest = $tnum;
 4059:                 if ($tsec ne '') {
 4060:                     $area .= '/'.$tsec;
 4061:                     $trest .= '/'.$tsec;
 4062:                 }
 4063:                 $spec = $trole.'.'.$area;
 4064:                 if ($trole =~ /^cr/) {
 4065:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4066:                                                       $tdom,$spec,$trest,$area);
 4067:                 } else {
 4068:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4069:                                                        $tdom,$spec,$trest,$area);
 4070:                 }
 4071:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4072:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4073:                     if ($1) {
 4074:                         $no_userblock = 1;
 4075:                         last;
 4076:                     }
 4077:                 }
 4078:             } else {
 4079:                 # Resource belongs to current user
 4080:                 # Check for 'evb' priv via lonnet::allowed().
 4081:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4082:                     $no_ownblock = 1;
 4083:                     last;
 4084:                 }
 4085:             }
 4086:         }
 4087:         # if they have the evb priv and are currently not playing student
 4088:         next if (($no_ownblock) &&
 4089:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4090:         next if ($no_userblock);
 4091: 
 4092:         # Retrieve blocking times and identity of locker for course
 4093:         # of specified user, unless user has 'evb' privilege.
 4094:         
 4095:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4096:         if (($start != 0) && 
 4097:             (($startblock == 0) || ($startblock > $start))) {
 4098:             $startblock = $start;
 4099:         }
 4100:         if (($end != 0)  &&
 4101:             (($endblock == 0) || ($endblock < $end))) {
 4102:             $endblock = $end;
 4103:         }
 4104:     }
 4105:     return ($startblock,$endblock);
 4106: }
 4107: 
 4108: sub get_blocks {
 4109:     my ($setters,$activity,$cdom,$cnum) = @_;
 4110:     my $startblock = 0;
 4111:     my $endblock = 0;
 4112:     my $course = $cdom.'_'.$cnum;
 4113:     $setters->{$course} = {};
 4114:     $setters->{$course}{'staff'} = [];
 4115:     $setters->{$course}{'times'} = [];
 4116:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4117:     foreach my $record (keys(%records)) {
 4118:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4119:         if ($start <= time && $end >= time) {
 4120:             my ($staff_name,$staff_dom,$title,$blocks) =
 4121:                 &parse_block_record($records{$record});
 4122:             if ($blocks->{$activity} eq 'on') {
 4123:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4124:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4125:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4126:                     $startblock = $start;
 4127:                 }
 4128:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4129:                     $endblock = $end;
 4130:                 }
 4131:             }
 4132:         }
 4133:     }
 4134:     return ($startblock,$endblock);
 4135: }
 4136: 
 4137: sub parse_block_record {
 4138:     my ($record) = @_;
 4139:     my ($setuname,$setudom,$title,$blocks);
 4140:     if (ref($record) eq 'HASH') {
 4141:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4142:         $title = &unescape($record->{'event'});
 4143:         $blocks = $record->{'blocks'};
 4144:     } else {
 4145:         my @data = split(/:/,$record,3);
 4146:         if (scalar(@data) eq 2) {
 4147:             $title = $data[1];
 4148:             ($setuname,$setudom) = split(/@/,$data[0]);
 4149:         } else {
 4150:             ($setuname,$setudom,$title) = @data;
 4151:         }
 4152:         $blocks = { 'com' => 'on' };
 4153:     }
 4154:     return ($setuname,$setudom,$title,$blocks);
 4155: }
 4156: 
 4157: sub blocking_status {
 4158:   my ($activity,$uname,$udom) = @_;
 4159:   my %setters;
 4160: 
 4161:   # check for active blocking
 4162:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4163: 
 4164:   my $blocked = $startblock && $endblock ? 1 : 0;
 4165: 
 4166:   # caller just wants to know whether a block is active
 4167:   if (!wantarray) { return $blocked; }
 4168: 
 4169:   # build a link to a popup window containing the details
 4170:   my $querystring  = "?activity=$activity";
 4171:   # $uname and $udom decide whose portfolio the user is trying to look at
 4172:      $querystring .= "&amp;udom=$udom"      if $udom;
 4173:      $querystring .= "&amp;uname=$uname"    if $uname;
 4174: 
 4175:   my $output .= <<'END_MYBLOCK';
 4176:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4177:         var options = "width=" + w + ",height=" + h + ",";
 4178:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4179:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4180:         var newWin = window.open(url, wdwName, options);
 4181:         newWin.focus();
 4182:     }
 4183: END_MYBLOCK
 4184: 
 4185:   $output = Apache::lonhtmlcommon::scripttag($output);
 4186:   
 4187:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4188:   my $text = mt('Communication Blocked');
 4189: 
 4190:   $output .= <<"END_BLOCK";
 4191: <div class='LC_comblock'>
 4192:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4193:   title='$text'>
 4194:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4195:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4196:   title='$text'>$text</a>
 4197: </div>
 4198: 
 4199: END_BLOCK
 4200: 
 4201:   return ($blocked, $output);
 4202: }
 4203: 
 4204: ###############################################
 4205: 
 4206: sub check_ip_acc {
 4207:     my ($acc)=@_;
 4208:     &Apache::lonxml::debug("acc is $acc");
 4209:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4210:         return 1;
 4211:     }
 4212:     my $allowed=0;
 4213:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4214: 
 4215:     my $name;
 4216:     foreach my $pattern (split(',',$acc)) {
 4217:         $pattern =~ s/^\s*//;
 4218:         $pattern =~ s/\s*$//;
 4219:         if ($pattern =~ /\*$/) {
 4220:             #35.8.*
 4221:             $pattern=~s/\*//;
 4222:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4223:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4224:             #35.8.3.[34-56]
 4225:             my $low=$2;
 4226:             my $high=$3;
 4227:             $pattern=$1;
 4228:             if ($ip =~ /^\Q$pattern\E/) {
 4229:                 my $last=(split(/\./,$ip))[3];
 4230:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4231:             }
 4232:         } elsif ($pattern =~ /^\*/) {
 4233:             #*.msu.edu
 4234:             $pattern=~s/\*//;
 4235:             if (!defined($name)) {
 4236:                 use Socket;
 4237:                 my $netaddr=inet_aton($ip);
 4238:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4239:             }
 4240:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4241:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4242:             #127.0.0.1
 4243:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4244:         } else {
 4245:             #some.name.com
 4246:             if (!defined($name)) {
 4247:                 use Socket;
 4248:                 my $netaddr=inet_aton($ip);
 4249:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4250:             }
 4251:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4252:         }
 4253:         if ($allowed) { last; }
 4254:     }
 4255:     return $allowed;
 4256: }
 4257: 
 4258: ###############################################
 4259: 
 4260: =pod
 4261: 
 4262: =head1 Domain Template Functions
 4263: 
 4264: =over 4
 4265: 
 4266: =item * &determinedomain()
 4267: 
 4268: Inputs: $domain (usually will be undef)
 4269: 
 4270: Returns: Determines which domain should be used for designs
 4271: 
 4272: =cut
 4273: 
 4274: ###############################################
 4275: sub determinedomain {
 4276:     my $domain=shift;
 4277:     if (! $domain) {
 4278:         # Determine domain if we have not been given one
 4279:         $domain = &Apache::lonnet::default_login_domain();
 4280:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4281:         if ($env{'request.role.domain'}) { 
 4282:             $domain=$env{'request.role.domain'}; 
 4283:         }
 4284:     }
 4285:     return $domain;
 4286: }
 4287: ###############################################
 4288: 
 4289: sub devalidate_domconfig_cache {
 4290:     my ($udom)=@_;
 4291:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4292: }
 4293: 
 4294: # ---------------------- Get domain configuration for a domain
 4295: sub get_domainconf {
 4296:     my ($udom) = @_;
 4297:     my $cachetime=1800;
 4298:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4299:     if (defined($cached)) { return %{$result}; }
 4300: 
 4301:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4302: 					     ['login','rolecolors','autoenroll'],$udom);
 4303:     my (%designhash,%legacy);
 4304:     if (keys(%domconfig) > 0) {
 4305:         if (ref($domconfig{'login'}) eq 'HASH') {
 4306:             if (keys(%{$domconfig{'login'}})) {
 4307:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4308:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4309:                         if ($key eq 'loginvia') {
 4310:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4311:                                 my @ids = &Apache::lonnet::current_machine_ids();
 4312:                                 foreach my $hostname (@ids) {
 4313:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4314:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4315:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4316:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4317:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4318: 
 4319:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4320:                                             } else {
 4321:                                                  $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4322:                                             }
 4323:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4324:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4325:                                             }
 4326:                                         }
 4327:                                     }
 4328:                                 }
 4329:                             }
 4330:                         } else {
 4331:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4332:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4333:                                     $domconfig{'login'}{$key}{$img};
 4334:                             }
 4335:                         }
 4336:                     } else {
 4337:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4338:                     }
 4339:                 }
 4340:             } else {
 4341:                 $legacy{'login'} = 1;
 4342:             }
 4343:         } else {
 4344:             $legacy{'login'} = 1;
 4345:         }
 4346:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4347:             if (keys(%{$domconfig{'rolecolors'}})) {
 4348:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4349:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4350:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4351:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4352:                         }
 4353:                     }
 4354:                 }
 4355:             } else {
 4356:                 $legacy{'rolecolors'} = 1;
 4357:             }
 4358:         } else {
 4359:             $legacy{'rolecolors'} = 1;
 4360:         }
 4361:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4362:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4363:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4364:             }
 4365:         }
 4366:         if (keys(%legacy) > 0) {
 4367:             my %legacyhash = &get_legacy_domconf($udom);
 4368:             foreach my $item (keys(%legacyhash)) {
 4369:                 if ($item =~ /^\Q$udom\E\.login/) {
 4370:                     if ($legacy{'login'}) { 
 4371:                         $designhash{$item} = $legacyhash{$item};
 4372:                     }
 4373:                 } else {
 4374:                     if ($legacy{'rolecolors'}) {
 4375:                         $designhash{$item} = $legacyhash{$item};
 4376:                     }
 4377:                 }
 4378:             }
 4379:         }
 4380:     } else {
 4381:         %designhash = &get_legacy_domconf($udom); 
 4382:     }
 4383:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4384: 				  $cachetime);
 4385:     return %designhash;
 4386: }
 4387: 
 4388: sub get_legacy_domconf {
 4389:     my ($udom) = @_;
 4390:     my %legacyhash;
 4391:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4392:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4393:     if (-e $designfile) {
 4394:         if ( open (my $fh,"<$designfile") ) {
 4395:             while (my $line = <$fh>) {
 4396:                 next if ($line =~ /^\#/);
 4397:                 chomp($line);
 4398:                 my ($key,$val)=(split(/\=/,$line));
 4399:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4400:             }
 4401:             close($fh);
 4402:         }
 4403:     }
 4404:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4405:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4406:     }
 4407:     return %legacyhash;
 4408: }
 4409: 
 4410: =pod
 4411: 
 4412: =item * &domainlogo()
 4413: 
 4414: Inputs: $domain (usually will be undef)
 4415: 
 4416: Returns: A link to a domain logo, if the domain logo exists.
 4417: If the domain logo does not exist, a description of the domain.
 4418: 
 4419: =cut
 4420: 
 4421: ###############################################
 4422: sub domainlogo {
 4423:     my $domain = &determinedomain(shift);
 4424:     my %designhash = &get_domainconf($domain);    
 4425:     # See if there is a logo
 4426:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4427:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4428:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4429: 	    if ($imgsrc =~ m{^/res/}) {
 4430: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4431: 		&Apache::lonnet::repcopy($local_name);
 4432: 	    }
 4433: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4434:         } 
 4435:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4436:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4437:         return &Apache::lonnet::domain($domain,'description');
 4438:     } else {
 4439:         return '';
 4440:     }
 4441: }
 4442: ##############################################
 4443: 
 4444: =pod
 4445: 
 4446: =item * &designparm()
 4447: 
 4448: Inputs: $which parameter; $domain (usually will be undef)
 4449: 
 4450: Returns: value of designparamter $which
 4451: 
 4452: =cut
 4453: 
 4454: 
 4455: ##############################################
 4456: sub designparm {
 4457:     my ($which,$domain)=@_;
 4458:     if (exists($env{'environment.color.'.$which})) {
 4459:         return $env{'environment.color.'.$which};
 4460:     }
 4461:     $domain=&determinedomain($domain);
 4462:     my %domdesign = &get_domainconf($domain);
 4463:     my $output;
 4464:     if ($domdesign{$domain.'.'.$which} ne '') {
 4465:         $output = $domdesign{$domain.'.'.$which};
 4466:     } else {
 4467:         $output = $defaultdesign{$which};
 4468:     }
 4469:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4470:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4471:         if ($output =~ m{^/(adm|res)/}) {
 4472:             if ($output =~ m{^/res/}) {
 4473:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4474:                 &Apache::lonnet::repcopy($local_name);
 4475:             }
 4476:             $output = &lonhttpdurl($output);
 4477:         }
 4478:     }
 4479:     return $output;
 4480: }
 4481: 
 4482: ##############################################
 4483: =pod
 4484: 
 4485: =item * &authorspace()
 4486: 
 4487: Inputs: ./.
 4488: 
 4489: Returns: Path to the Construction Space of the current user's
 4490:          accessed author space
 4491:          The author space will be that of the current user
 4492:          when accessing the own author space
 4493:          and that of the co-author/assistent co-author
 4494:          when accessing the co-author's/assistent co-author's
 4495:          space
 4496: 
 4497: =cut
 4498: 
 4499: sub authorspace {
 4500:     my $caname = '';
 4501:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4502:         (undef,$caname) =
 4503:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4504:     } else {
 4505:         $caname = $env{'user.name'};
 4506:     }
 4507:     return '/priv/'.$caname.'/';
 4508: }
 4509: 
 4510: ##############################################
 4511: =pod
 4512: 
 4513: =item * &head_subbox()
 4514: 
 4515: Inputs: $content (contains HTML code with page functions, etc.)
 4516: 
 4517: Returns: HTML div with $content
 4518:          To be included in page header
 4519: 
 4520: =cut
 4521: 
 4522: sub head_subbox {
 4523:     my ($content)=@_;
 4524:     my $output =
 4525:         '<div class="LC_head_subbox">'
 4526:        .$content
 4527:        .'</div>'
 4528: }
 4529: 
 4530: ##############################################
 4531: =pod
 4532: 
 4533: =item * &CSTR_pageheader()
 4534: 
 4535: Inputs: ./.
 4536: 
 4537: Returns: HTML div with CSTR path and recent box
 4538:          To be included on Construction Space pages
 4539: 
 4540: =cut
 4541: 
 4542: sub CSTR_pageheader {
 4543:     # this is for resources; directories have customtitle, and crumbs
 4544:             # and select recent are created in lonpubdir.pm  
 4545:     my ($uname,$thisdisfn)=
 4546:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4547:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4548:     $formaction=~s/\/+/\//g;
 4549: 
 4550:     my $parentpath = '';
 4551:     my $lastitem = '';
 4552:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4553:         $parentpath = $1;
 4554:         $lastitem = $2;
 4555:     } else {
 4556:         $lastitem = $thisdisfn;
 4557:     }
 4558: 
 4559:     my $output =
 4560:          '<div>'
 4561:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4562:         .'<b>'.&mt('Construction Space:').'</b> '
 4563:         .'<form name="dirs" method="post" action="'.$formaction
 4564:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4565:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
 4566: 
 4567:     if ($lastitem) {
 4568:         $output .=
 4569:              '<span class="LC_filename">'
 4570:             .$lastitem
 4571:             .'</span>';
 4572:     }
 4573:     $output .=
 4574:          '<br />'
 4575:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4576:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4577:         .'</form>'
 4578:         .&Apache::lonmenu::constspaceform()
 4579:         .'</div>';
 4580: 
 4581:     return $output;
 4582: }
 4583: 
 4584: ###############################################
 4585: ###############################################
 4586: 
 4587: =pod
 4588: 
 4589: =back
 4590: 
 4591: =head1 HTML Helpers
 4592: 
 4593: =over 4
 4594: 
 4595: =item * &bodytag()
 4596: 
 4597: Returns a uniform header for LON-CAPA web pages.
 4598: 
 4599: Inputs: 
 4600: 
 4601: =over 4
 4602: 
 4603: =item * $title, A title to be displayed on the page.
 4604: 
 4605: =item * $function, the current role (can be undef).
 4606: 
 4607: =item * $addentries, extra parameters for the <body> tag.
 4608: 
 4609: =item * $bodyonly, if defined, only return the <body> tag.
 4610: 
 4611: =item * $domain, if defined, force a given domain.
 4612: 
 4613: =item * $forcereg, if page should register as content page (relevant for 
 4614:             text interface only)
 4615: 
 4616: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4617:                      navigational links
 4618: 
 4619: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4620: 
 4621: =item * $args, optional argument valid values are
 4622:             no_auto_mt_title -> prevents &mt()ing the title arg
 4623:             inherit_jsmath -> when creating popup window in a page,
 4624:                               should it have jsmath forced on by the
 4625:                               current page
 4626: 
 4627: =back
 4628: 
 4629: Returns: A uniform header for LON-CAPA web pages.  
 4630: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4631: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4632: other decorations will be returned.
 4633: 
 4634: =cut
 4635: 
 4636: sub bodytag {
 4637:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4638:         $no_nav_bar,$bgcolor,$args)=@_;
 4639: 
 4640:     my $public;
 4641:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4642:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4643:         $public = 1;
 4644:     }
 4645:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4646: 
 4647:     $function = &get_users_function() if (!$function);
 4648:     my $img =    &designparm($function.'.img',$domain);
 4649:     my $font =   &designparm($function.'.font',$domain);
 4650:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4651: 
 4652:     my %design = ( 'style'   => 'margin-top: 0',
 4653: 		   'bgcolor' => $pgbg,
 4654: 		   'text'    => $font,
 4655:                    'alink'   => &designparm($function.'.alink',$domain),
 4656: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4657: 		   'link'    => &designparm($function.'.link',$domain),);
 4658:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4659: 
 4660:  # role and realm
 4661:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4662:     if ($role  eq 'ca') {
 4663:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4664:         $realm = &plainname($rname,$rdom);
 4665:     } 
 4666: # realm
 4667:     if ($env{'request.course.id'}) {
 4668:         if ($env{'request.role'} !~ /^cr/) {
 4669:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4670:         }
 4671:         if ($env{'request.course.sec'}) {
 4672:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4673:         }   
 4674: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4675:     } else {
 4676:         $role = &Apache::lonnet::plaintext($role);
 4677:     }
 4678: 
 4679:     if (!$realm) { $realm='&nbsp;'; }
 4680: 
 4681:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4682: 
 4683: # construct main body tag
 4684:     my $bodytag = "<body $extra_body_attr>".
 4685: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4686: 
 4687:     if ($bodyonly) {
 4688:         return $bodytag;
 4689:     } 
 4690: 
 4691:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4692:     if ($public) {
 4693: 	undef($role);
 4694:     } else {
 4695: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4696:     }
 4697:     
 4698:     my $titleinfo = '<h1>'.$title.'</h1>';
 4699:     #
 4700:     # Extra info if you are the DC
 4701:     my $dc_info = '';
 4702:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4703:                         $env{'course.'.$env{'request.course.id'}.
 4704:                                  '.domain'}.'/'})) {
 4705:         my $cid = $env{'request.course.id'};
 4706:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4707:         $dc_info =~ s/\s+$//;
 4708:     }
 4709: 
 4710:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4711:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4712: 
 4713:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4714:             return $bodytag; 
 4715:         } 
 4716: 
 4717:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4718: 
 4719:         #    if ($env{'request.state'} eq 'construct') {
 4720:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4721:         #    }
 4722: 
 4723: 
 4724: 
 4725:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4726:              if ($dc_info) {
 4727:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4728:              }
 4729:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4730:                 <em>$realm</em> $dc_info</div>|;
 4731:             return $bodytag;
 4732:         }
 4733: 
 4734:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4735:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4736:         }
 4737: 
 4738:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4739:             Apache::lonmenu::utilityfunctions(), 'start');
 4740: 
 4741:         $bodytag .= Apache::lonmenu::primary_menu();
 4742: 
 4743:         if ($dc_info) {
 4744:             $dc_info = &dc_courseid_toggle($dc_info);
 4745:         }
 4746:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4747: 
 4748:         #don't show menus for public users
 4749:         if (!$public){
 4750:             $bodytag .= Apache::lonmenu::secondary_menu();
 4751:             $bodytag .= Apache::lonmenu::serverform();
 4752:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4753:             if ($env{'request.state'} eq 'construct') {
 4754:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 4755:                                 $args->{'bread_crumbs'});
 4756:             } elsif ($forcereg) { 
 4757:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4758:             }
 4759:         }else{
 4760:             # this is to seperate menu from content when there's no secondary
 4761:             # menu. Especially needed for public accessible ressources.
 4762:             $bodytag .= '<hr style="clear:both" />';
 4763:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4764:         }
 4765: 
 4766:         return $bodytag;
 4767: }
 4768: 
 4769: sub dc_courseid_toggle {
 4770:     my ($dc_info) = @_;
 4771:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 4772:            '<a href="javascript:showCourseID();">'.
 4773:            &mt('(More ...)').'</a></span>'.
 4774:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4775: }
 4776: 
 4777: sub make_attr_string {
 4778:     my ($register,$attr_ref) = @_;
 4779: 
 4780:     if ($attr_ref && !ref($attr_ref)) {
 4781: 	die("addentries Must be a hash ref ".
 4782: 	    join(':',caller(1))." ".
 4783: 	    join(':',caller(0))." ");
 4784:     }
 4785: 
 4786:     if ($register) {
 4787: 	my ($on_load,$on_unload);
 4788: 	foreach my $key (keys(%{$attr_ref})) {
 4789: 	    if      (lc($key) eq 'onload') {
 4790: 		$on_load.=$attr_ref->{$key}.';';
 4791: 		delete($attr_ref->{$key});
 4792: 
 4793: 	    } elsif (lc($key) eq 'onunload') {
 4794: 		$on_unload.=$attr_ref->{$key}.';';
 4795: 		delete($attr_ref->{$key});
 4796: 	    }
 4797: 	}
 4798: 	$attr_ref->{'onload'}  = $on_load;
 4799: 	$attr_ref->{'onunload'}= $on_unload;
 4800:     }
 4801: 
 4802:     my $attr_string;
 4803:     foreach my $attr (keys(%$attr_ref)) {
 4804: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4805:     }
 4806:     return $attr_string;
 4807: }
 4808: 
 4809: 
 4810: ###############################################
 4811: ###############################################
 4812: 
 4813: =pod
 4814: 
 4815: =item * &endbodytag()
 4816: 
 4817: Returns a uniform footer for LON-CAPA web pages.
 4818: 
 4819: Inputs: 1 - optional reference to an args hash
 4820: If in the hash, key for noredirectlink has a value which evaluates to true,
 4821: a 'Continue' link is not displayed if the page contains an
 4822: internal redirect in the <head></head> section,
 4823: i.e., $env{'internal.head.redirect'} exists   
 4824: 
 4825: =cut
 4826: 
 4827: sub endbodytag {
 4828:     my ($args) = @_;
 4829:     my $endbodytag='</body>';
 4830:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4831:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4832:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4833: 	    $endbodytag=
 4834: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4835: 	        &mt('Continue').'</a>'.
 4836: 	        $endbodytag;
 4837:         }
 4838:     }
 4839:     return $endbodytag;
 4840: }
 4841: 
 4842: =pod
 4843: 
 4844: =item * &standard_css()
 4845: 
 4846: Returns a style sheet
 4847: 
 4848: Inputs: (all optional)
 4849:             domain         -> force to color decorate a page for a specific
 4850:                                domain
 4851:             function       -> force usage of a specific rolish color scheme
 4852:             bgcolor        -> override the default page bgcolor
 4853: 
 4854: =cut
 4855: 
 4856: sub standard_css {
 4857:     my ($function,$domain,$bgcolor) = @_;
 4858:     $function  = &get_users_function() if (!$function);
 4859:     my $img    = &designparm($function.'.img',   $domain);
 4860:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4861:     my $font   = &designparm($function.'.font',  $domain);
 4862:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4863: #second colour for later usage
 4864:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4865:     my $pgbg_or_bgcolor =
 4866: 	         $bgcolor ||
 4867: 	         &designparm($function.'.pgbg',  $domain);
 4868:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4869:     my $alink  = &designparm($function.'.alink', $domain);
 4870:     my $vlink  = &designparm($function.'.vlink', $domain);
 4871:     my $link   = &designparm($function.'.link',  $domain);
 4872: 
 4873:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4874:     my $mono                 = 'monospace';
 4875:     my $data_table_head      = $sidebg;
 4876:     my $data_table_light     = '#FAFAFA';
 4877:     my $data_table_dark      = '#F0F0F0';
 4878:     my $data_table_darker    = '#CCCCCC';
 4879:     my $data_table_highlight = '#FFFF00';
 4880:     my $mail_new             = '#FFBB77';
 4881:     my $mail_new_hover       = '#DD9955';
 4882:     my $mail_read            = '#BBBB77';
 4883:     my $mail_read_hover      = '#999944';
 4884:     my $mail_replied         = '#AAAA88';
 4885:     my $mail_replied_hover   = '#888855';
 4886:     my $mail_other           = '#99BBBB';
 4887:     my $mail_other_hover     = '#669999';
 4888:     my $table_header         = '#DDDDDD';
 4889:     my $feedback_link_bg     = '#BBBBBB';
 4890:     my $lg_border_color      = '#C8C8C8';
 4891:     my $button_hover         = '#BF2317';
 4892: 
 4893:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4894:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4895:                                              : '0 3px 0 4px';
 4896: 
 4897: 
 4898:     return <<END;
 4899: 
 4900: /* needed for iframe to allow 100% height in FF */
 4901: body, html { 
 4902:     margin: 0;
 4903:     padding: 0 0.5%;
 4904:     height: 99%; /* to avoid scrollbars */
 4905: }
 4906: 
 4907: body {
 4908:   font-family: $sans;
 4909:   line-height:130%;
 4910:   font-size:0.83em;
 4911:   color:$font;
 4912: }
 4913: 
 4914: a:focus,
 4915: a:focus img {
 4916:   color: red;
 4917:   background: yellow;
 4918: }
 4919: 
 4920: form, .inline {
 4921:   display: inline;
 4922: }
 4923: 
 4924: .LC_right {
 4925:   text-align:right;
 4926: }
 4927: 
 4928: .LC_middle {
 4929:   vertical-align:middle;
 4930: }
 4931: 
 4932: .LC_400Box {
 4933:   width:400px;
 4934: }
 4935: 
 4936: .LC_iframecontainer {
 4937:     width: 98%;
 4938:     margin: 0;
 4939:     position: fixed;
 4940:     top: 8.5em;
 4941:     bottom: 0;
 4942: }
 4943: 
 4944: .LC_iframecontainer iframe{
 4945:     border: none;
 4946:     width: 100%;
 4947:     height: 100%;
 4948: }
 4949: 
 4950: .LC_filename {
 4951:   font-family: $mono;
 4952:   white-space:pre;
 4953:   font-size: 120%;
 4954: }
 4955: 
 4956: .LC_fileicon {
 4957:   border: none;
 4958:   height: 1.3em;
 4959:   vertical-align: text-bottom;
 4960:   margin-right: 0.3em;
 4961:   text-decoration:none;
 4962: }
 4963: 
 4964: .LC_setting {
 4965:   text-decoration:underline;
 4966: }
 4967: 
 4968: .LC_error {
 4969:   color: red;
 4970:   font-size: larger;
 4971: }
 4972: 
 4973: .LC_warning,
 4974: .LC_diff_removed {
 4975:   color: red;
 4976: }
 4977: 
 4978: .LC_info,
 4979: .LC_success,
 4980: .LC_diff_added {
 4981:   color: green;
 4982: }
 4983: 
 4984: div.LC_confirm_box {
 4985:   background-color: #FAFAFA;
 4986:   border: 1px solid $lg_border_color;
 4987:   margin-right: 0;
 4988:   padding: 5px;
 4989: }
 4990: 
 4991: div.LC_confirm_box .LC_error img,
 4992: div.LC_confirm_box .LC_success img {
 4993:   vertical-align: middle;
 4994: }
 4995: 
 4996: .LC_icon {
 4997:   border: none;
 4998:   vertical-align: middle;
 4999: }
 5000: 
 5001: .LC_docs_spacer {
 5002:   width: 25px;
 5003:   height: 1px;
 5004:   border: none;
 5005: }
 5006: 
 5007: .LC_internal_info {
 5008:   color: #999999;
 5009: }
 5010: 
 5011: .LC_discussion {
 5012:   background: $tabbg;
 5013:   border: 1px solid black;
 5014:   margin: 2px;
 5015: }
 5016: 
 5017: .LC_disc_action_links_bar {
 5018:   background: $tabbg;
 5019:   border: none;
 5020:   margin: 4px;
 5021: }
 5022: 
 5023: .LC_disc_action_left {
 5024:   text-align: left;
 5025: }
 5026: 
 5027: .LC_disc_action_right {
 5028:   text-align: right;
 5029: }
 5030: 
 5031: .LC_disc_new_item {
 5032:   background: white;
 5033:   border: 2px solid red;
 5034:   margin: 2px;
 5035: }
 5036: 
 5037: .LC_disc_old_item {
 5038:   background: white;
 5039:   border: 1px solid black;
 5040:   margin: 2px;
 5041: }
 5042: 
 5043: table.LC_pastsubmission {
 5044:   border: 1px solid black;
 5045:   margin: 2px;
 5046: }
 5047: 
 5048: table#LC_menubuttons {
 5049:   width: 100%;
 5050:   background: $pgbg;
 5051:   border: 2px;
 5052:   border-collapse: separate;
 5053:   padding: 0;
 5054: }
 5055: 
 5056: table#LC_title_bar a {
 5057:   color: $fontmenu;
 5058: }
 5059: 
 5060: table#LC_title_bar {
 5061:   clear: both;
 5062:   display: none;
 5063: }
 5064: 
 5065: table#LC_title_bar,
 5066: table.LC_breadcrumbs, /* obsolete? */
 5067: table#LC_title_bar.LC_with_remote {
 5068:   width: 100%;
 5069:   border-color: $pgbg;
 5070:   border-style: solid;
 5071:   border-width: $border;
 5072:   background: $pgbg;
 5073:   color: $fontmenu;
 5074:   border-collapse: collapse;
 5075:   padding: 0;
 5076:   margin: 0;
 5077: }
 5078: 
 5079: ul.LC_breadcrumb_tools_outerlist {
 5080:     margin: 0;
 5081:     padding: 0;
 5082:     position: relative;
 5083:     list-style: none;
 5084: }
 5085: ul.LC_breadcrumb_tools_outerlist li {
 5086:     display: inline;
 5087: }
 5088: 
 5089: .LC_breadcrumb_tools_navigation {
 5090:     padding: 0;
 5091:     margin: 0;
 5092:     float: left;
 5093: }
 5094: .LC_breadcrumb_tools_tools {
 5095:     padding: 0;
 5096:     margin: 0;
 5097:     float: right;
 5098: }
 5099: 
 5100: table#LC_title_bar td {
 5101:   background: $tabbg;
 5102: }
 5103: 
 5104: table#LC_menubuttons img {
 5105:   border: none;
 5106: }
 5107: 
 5108: .LC_breadcrumbs_component {
 5109:   float: right;
 5110:   margin: 0 1em;
 5111: }
 5112: .LC_breadcrumbs_component img {
 5113:   vertical-align: middle;
 5114: }
 5115: 
 5116: td.LC_table_cell_checkbox {
 5117:   text-align: center;
 5118: }
 5119: 
 5120: .LC_fontsize_small {
 5121:   font-size: 70%;
 5122: }
 5123: 
 5124: #LC_breadcrumbs {
 5125:   clear:both;
 5126:   background: $sidebg;
 5127:   border-bottom: 1px solid $lg_border_color;
 5128:   line-height: 2.5em;
 5129:   overflow: hidden;
 5130:   margin: 0;
 5131:   padding: 0;
 5132:   text-align: left;
 5133: }
 5134: 
 5135: .LC_head_subbox {
 5136:   clear:both;
 5137:   background: #F8F8F8; /* $sidebg; */
 5138:   border: 1px solid $sidebg;
 5139:   margin: 0 0 10px 0;      
 5140:   padding: 3px;
 5141:   text-align: left;
 5142: }
 5143: 
 5144: .LC_fontsize_medium {
 5145:   font-size: 85%;
 5146: }
 5147: 
 5148: .LC_fontsize_large {
 5149:   font-size: 120%;
 5150: }
 5151: 
 5152: .LC_menubuttons_inline_text {
 5153:   color: $font;
 5154:   font-size: 90%;
 5155:   padding-left:3px;
 5156: }
 5157: 
 5158: .LC_menubuttons_inline_text img{
 5159:   vertical-align: middle;
 5160: }
 5161: 
 5162: li.LC_menubuttons_inline_text img,a {
 5163:   cursor:pointer;
 5164:   text-decoration: none;
 5165: }
 5166: 
 5167: .LC_menubuttons_link {
 5168:   text-decoration: none;
 5169: }
 5170: 
 5171: .LC_menubuttons_category {
 5172:   color: $font;
 5173:   background: $pgbg;
 5174:   font-size: larger;
 5175:   font-weight: bold;
 5176: }
 5177: 
 5178: td.LC_menubuttons_text {
 5179:   color: $font;
 5180: }
 5181: 
 5182: .LC_current_location {
 5183:   background: $tabbg;
 5184: }
 5185: 
 5186: table.LC_data_table {
 5187:   border: 1px solid #000000;
 5188:   border-collapse: separate;
 5189:   border-spacing: 1px;
 5190:   background: $pgbg;
 5191: }
 5192: 
 5193: .LC_data_table_dense {
 5194:   font-size: small;
 5195: }
 5196: 
 5197: table.LC_nested_outer {
 5198:   border: 1px solid #000000;
 5199:   border-collapse: collapse;
 5200:   border-spacing: 0;
 5201:   width: 100%;
 5202: }
 5203: 
 5204: table.LC_innerpickbox,
 5205: table.LC_nested {
 5206:   border: none;
 5207:   border-collapse: collapse;
 5208:   border-spacing: 0;
 5209:   width: 100%;
 5210: }
 5211: 
 5212: table.LC_data_table tr th,
 5213: table.LC_calendar tr th,
 5214: table.LC_prior_tries tr th,
 5215: table.LC_innerpickbox tr th {
 5216:   font-weight: bold;
 5217:   background-color: $data_table_head;
 5218:   color:$fontmenu;
 5219:   font-size:90%;
 5220: }
 5221: 
 5222: table.LC_innerpickbox tr th,
 5223: table.LC_innerpickbox tr td {
 5224:   vertical-align: top;
 5225: }
 5226: 
 5227: table.LC_data_table tr.LC_info_row > td {
 5228:   background-color: #CCCCCC;
 5229:   font-weight: bold;
 5230:   text-align: left;
 5231: }
 5232: 
 5233: table.LC_data_table tr.LC_odd_row > td {
 5234:   background-color: $data_table_light;
 5235:   padding: 2px;
 5236:   vertical-align: top;
 5237: }
 5238: 
 5239: table.LC_pick_box tr > td.LC_odd_row {
 5240:   background-color: $data_table_light;
 5241:   vertical-align: top;
 5242: }
 5243: 
 5244: table.LC_data_table tr.LC_even_row > td {
 5245:   background-color: $data_table_dark;
 5246:   padding: 2px;
 5247:   vertical-align: top;
 5248: }
 5249: 
 5250: table.LC_pick_box tr > td.LC_even_row {
 5251:   background-color: $data_table_dark;
 5252:   vertical-align: top;
 5253: }
 5254: 
 5255: table.LC_data_table tr.LC_data_table_highlight td {
 5256:   background-color: $data_table_darker;
 5257: }
 5258: 
 5259: table.LC_data_table tr td.LC_leftcol_header {
 5260:   background-color: $data_table_head;
 5261:   font-weight: bold;
 5262: }
 5263: 
 5264: table.LC_data_table tr.LC_empty_row td,
 5265: table.LC_nested tr.LC_empty_row td {
 5266:   font-weight: bold;
 5267:   font-style: italic;
 5268:   text-align: center;
 5269:   padding: 8px;
 5270: }
 5271: 
 5272: table.LC_data_table tr.LC_empty_row td {
 5273:   background-color: $sidebg;
 5274: }
 5275: 
 5276: table.LC_nested tr.LC_empty_row td {
 5277:   background-color: #FFFFFF;
 5278: }
 5279: 
 5280: table.LC_caption {
 5281: }
 5282: 
 5283: table.LC_nested tr.LC_empty_row td {
 5284:   padding: 4ex
 5285: }
 5286: 
 5287: table.LC_nested_outer tr th {
 5288:   font-weight: bold;
 5289:   color:$fontmenu;
 5290:   background-color: $data_table_head;
 5291:   font-size: small;
 5292:   border-bottom: 1px solid #000000;
 5293: }
 5294: 
 5295: table.LC_nested_outer tr td.LC_subheader {
 5296:   background-color: $data_table_head;
 5297:   font-weight: bold;
 5298:   font-size: small;
 5299:   border-bottom: 1px solid #000000;
 5300:   text-align: right;
 5301: }
 5302: 
 5303: table.LC_nested tr.LC_info_row td {
 5304:   background-color: #CCCCCC;
 5305:   font-weight: bold;
 5306:   font-size: small;
 5307:   text-align: center;
 5308: }
 5309: 
 5310: table.LC_nested tr.LC_info_row td.LC_left_item,
 5311: table.LC_nested_outer tr th.LC_left_item {
 5312:   text-align: left;
 5313: }
 5314: 
 5315: table.LC_nested td {
 5316:   background-color: #FFFFFF;
 5317:   font-size: small;
 5318: }
 5319: 
 5320: table.LC_nested_outer tr th.LC_right_item,
 5321: table.LC_nested tr.LC_info_row td.LC_right_item,
 5322: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5323: table.LC_nested tr td.LC_right_item {
 5324:   text-align: right;
 5325: }
 5326: 
 5327: table.LC_nested tr.LC_odd_row td {
 5328:   background-color: #EEEEEE;
 5329: }
 5330: 
 5331: table.LC_createuser {
 5332: }
 5333: 
 5334: table.LC_createuser tr.LC_section_row td {
 5335:   font-size: small;
 5336: }
 5337: 
 5338: table.LC_createuser tr.LC_info_row td  {
 5339:   background-color: #CCCCCC;
 5340:   font-weight: bold;
 5341:   text-align: center;
 5342: }
 5343: 
 5344: table.LC_calendar {
 5345:   border: 1px solid #000000;
 5346:   border-collapse: collapse;
 5347:   width: 98%;
 5348: }
 5349: 
 5350: table.LC_calendar_pickdate {
 5351:   font-size: xx-small;
 5352: }
 5353: 
 5354: table.LC_calendar tr td {
 5355:   border: 1px solid #000000;
 5356:   vertical-align: top;
 5357:   width: 14%;
 5358: }
 5359: 
 5360: table.LC_calendar tr td.LC_calendar_day_empty {
 5361:   background-color: $data_table_dark;
 5362: }
 5363: 
 5364: table.LC_calendar tr td.LC_calendar_day_current {
 5365:   background-color: $data_table_highlight;
 5366: }
 5367: 
 5368: table.LC_data_table tr td.LC_mail_new {
 5369:   background-color: $mail_new;
 5370: }
 5371: 
 5372: table.LC_data_table tr.LC_mail_new:hover {
 5373:   background-color: $mail_new_hover;
 5374: }
 5375: 
 5376: table.LC_data_table tr td.LC_mail_read {
 5377:   background-color: $mail_read;
 5378: }
 5379: 
 5380: /*
 5381: table.LC_data_table tr.LC_mail_read:hover {
 5382:   background-color: $mail_read_hover;
 5383: }
 5384: */
 5385: 
 5386: table.LC_data_table tr td.LC_mail_replied {
 5387:   background-color: $mail_replied;
 5388: }
 5389: 
 5390: /*
 5391: table.LC_data_table tr.LC_mail_replied:hover {
 5392:   background-color: $mail_replied_hover;
 5393: }
 5394: */
 5395: 
 5396: table.LC_data_table tr td.LC_mail_other {
 5397:   background-color: $mail_other;
 5398: }
 5399: 
 5400: /*
 5401: table.LC_data_table tr.LC_mail_other:hover {
 5402:   background-color: $mail_other_hover;
 5403: }
 5404: */
 5405: 
 5406: table.LC_data_table tr > td.LC_browser_file,
 5407: table.LC_data_table tr > td.LC_browser_file_published {
 5408:   background: #AAEE77;
 5409: }
 5410: 
 5411: table.LC_data_table tr > td.LC_browser_file_locked,
 5412: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5413:   background: #FFAA99;
 5414: }
 5415: 
 5416: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5417:   background: #888888;
 5418: }
 5419: 
 5420: table.LC_data_table tr > td.LC_browser_file_modified,
 5421: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5422:   background: #F8F866;
 5423: }
 5424: 
 5425: table.LC_data_table tr.LC_browser_folder > td {
 5426:   background: #E0E8FF;
 5427: }
 5428: 
 5429: table.LC_data_table tr > td.LC_roles_is {
 5430:   /* background: #77FF77; */
 5431: }
 5432: 
 5433: table.LC_data_table tr > td.LC_roles_future {
 5434:   border-right: 8px solid #FFFF77;
 5435: }
 5436: 
 5437: table.LC_data_table tr > td.LC_roles_will {
 5438:   border-right: 8px solid #FFAA77;
 5439: }
 5440: 
 5441: table.LC_data_table tr > td.LC_roles_expired {
 5442:   border-right: 8px solid #FF7777;
 5443: }
 5444: 
 5445: table.LC_data_table tr > td.LC_roles_will_not {
 5446:   border-right: 8px solid #AAFF77;
 5447: }
 5448: 
 5449: table.LC_data_table tr > td.LC_roles_selected {
 5450:   border-right: 8px solid #11CC55;
 5451: }
 5452: 
 5453: span.LC_current_location {
 5454:   font-size:larger;
 5455:   background: $pgbg;
 5456: }
 5457: 
 5458: span.LC_parm_menu_item {
 5459:   font-size: larger;
 5460: }
 5461: 
 5462: span.LC_parm_scope_all {
 5463:   color: red;
 5464: }
 5465: 
 5466: span.LC_parm_scope_folder {
 5467:   color: green;
 5468: }
 5469: 
 5470: span.LC_parm_scope_resource {
 5471:   color: orange;
 5472: }
 5473: 
 5474: span.LC_parm_part {
 5475:   color: blue;
 5476: }
 5477: 
 5478: span.LC_parm_folder,
 5479: span.LC_parm_symb {
 5480:   font-size: x-small;
 5481:   font-family: $mono;
 5482:   color: #AAAAAA;
 5483: }
 5484: 
 5485: ul.LC_parm_parmlist li {
 5486:   display: inline-block;
 5487:   padding: 0.3em 0.8em;
 5488:   vertical-align: top;
 5489:   width: 150px;
 5490:   border-top:1px solid $lg_border_color;
 5491: }
 5492: 
 5493: td.LC_parm_overview_level_menu,
 5494: td.LC_parm_overview_map_menu,
 5495: td.LC_parm_overview_parm_selectors,
 5496: td.LC_parm_overview_restrictions  {
 5497:   border: 1px solid black;
 5498:   border-collapse: collapse;
 5499: }
 5500: 
 5501: table.LC_parm_overview_restrictions td {
 5502:   border-width: 1px 4px 1px 4px;
 5503:   border-style: solid;
 5504:   border-color: $pgbg;
 5505:   text-align: center;
 5506: }
 5507: 
 5508: table.LC_parm_overview_restrictions th {
 5509:   background: $tabbg;
 5510:   border-width: 1px 4px 1px 4px;
 5511:   border-style: solid;
 5512:   border-color: $pgbg;
 5513: }
 5514: 
 5515: table#LC_helpmenu {
 5516:   border: none;
 5517:   height: 55px;
 5518:   border-spacing: 0;
 5519: }
 5520: 
 5521: table#LC_helpmenu fieldset legend {
 5522:   font-size: larger;
 5523: }
 5524: 
 5525: table#LC_helpmenu_links {
 5526:   width: 100%;
 5527:   border: 1px solid black;
 5528:   background: $pgbg;
 5529:   padding: 0;
 5530:   border-spacing: 1px;
 5531: }
 5532: 
 5533: table#LC_helpmenu_links tr td {
 5534:   padding: 1px;
 5535:   background: $tabbg;
 5536:   text-align: center;
 5537:   font-weight: bold;
 5538: }
 5539: 
 5540: table#LC_helpmenu_links a:link,
 5541: table#LC_helpmenu_links a:visited,
 5542: table#LC_helpmenu_links a:active {
 5543:   text-decoration: none;
 5544:   color: $font;
 5545: }
 5546: 
 5547: table#LC_helpmenu_links a:hover {
 5548:   text-decoration: underline;
 5549:   color: $vlink;
 5550: }
 5551: 
 5552: .LC_chrt_popup_exists {
 5553:   border: 1px solid #339933;
 5554:   margin: -1px;
 5555: }
 5556: 
 5557: .LC_chrt_popup_up {
 5558:   border: 1px solid yellow;
 5559:   margin: -1px;
 5560: }
 5561: 
 5562: .LC_chrt_popup {
 5563:   border: 1px solid #8888FF;
 5564:   background: #CCCCFF;
 5565: }
 5566: 
 5567: table.LC_pick_box {
 5568:   border-collapse: separate;
 5569:   background: white;
 5570:   border: 1px solid black;
 5571:   border-spacing: 1px;
 5572: }
 5573: 
 5574: table.LC_pick_box td.LC_pick_box_title {
 5575:   background: $sidebg;
 5576:   font-weight: bold;
 5577:   text-align: left;
 5578:   vertical-align: top;
 5579:   width: 184px;
 5580:   padding: 8px;
 5581: }
 5582: 
 5583: table.LC_pick_box td.LC_pick_box_value {
 5584:   text-align: left;
 5585:   padding: 8px;
 5586: }
 5587: 
 5588: table.LC_pick_box td.LC_pick_box_select {
 5589:   text-align: left;
 5590:   padding: 8px;
 5591: }
 5592: 
 5593: table.LC_pick_box td.LC_pick_box_separator {
 5594:   padding: 0;
 5595:   height: 1px;
 5596:   background: black;
 5597: }
 5598: 
 5599: table.LC_pick_box td.LC_pick_box_submit {
 5600:   text-align: right;
 5601: }
 5602: 
 5603: table.LC_pick_box td.LC_evenrow_value {
 5604:   text-align: left;
 5605:   padding: 8px;
 5606:   background-color: $data_table_light;
 5607: }
 5608: 
 5609: table.LC_pick_box td.LC_oddrow_value {
 5610:   text-align: left;
 5611:   padding: 8px;
 5612:   background-color: $data_table_light;
 5613: }
 5614: 
 5615: span.LC_helpform_receipt_cat {
 5616:   font-weight: bold;
 5617: }
 5618: 
 5619: table.LC_group_priv_box {
 5620:   background: white;
 5621:   border: 1px solid black;
 5622:   border-spacing: 1px;
 5623: }
 5624: 
 5625: table.LC_group_priv_box td.LC_pick_box_title {
 5626:   background: $tabbg;
 5627:   font-weight: bold;
 5628:   text-align: right;
 5629:   width: 184px;
 5630: }
 5631: 
 5632: table.LC_group_priv_box td.LC_groups_fixed {
 5633:   background: $data_table_light;
 5634:   text-align: center;
 5635: }
 5636: 
 5637: table.LC_group_priv_box td.LC_groups_optional {
 5638:   background: $data_table_dark;
 5639:   text-align: center;
 5640: }
 5641: 
 5642: table.LC_group_priv_box td.LC_groups_functionality {
 5643:   background: $data_table_darker;
 5644:   text-align: center;
 5645:   font-weight: bold;
 5646: }
 5647: 
 5648: table.LC_group_priv td {
 5649:   text-align: left;
 5650:   padding: 0;
 5651: }
 5652: 
 5653: .LC_navbuttons {
 5654:   margin: 2ex 0ex 2ex 0ex;
 5655: }
 5656: 
 5657: .LC_topic_bar {
 5658:   font-weight: bold;
 5659:   background: $tabbg;
 5660:   margin: 1em 0em 1em 2em;
 5661:   padding: 3px;
 5662:   font-size: 1.2em;
 5663: }
 5664: 
 5665: .LC_topic_bar span {
 5666:   left: 0.5em;
 5667:   position: absolute;
 5668:   vertical-align: middle;
 5669:   font-size: 1.2em;
 5670: }
 5671: 
 5672: table.LC_course_group_status {
 5673:   margin: 20px;
 5674: }
 5675: 
 5676: table.LC_status_selector td {
 5677:   vertical-align: top;
 5678:   text-align: center;
 5679:   padding: 4px;
 5680: }
 5681: 
 5682: div.LC_feedback_link {
 5683:   clear: both;
 5684:   background: $sidebg;
 5685:   width: 100%;
 5686:   padding-bottom: 10px;
 5687:   border: 1px $tabbg solid;
 5688:   height: 22px;
 5689:   line-height: 22px;
 5690:   padding-top: 5px;
 5691: }
 5692: 
 5693: div.LC_feedback_link img {
 5694:   height: 22px;
 5695:   vertical-align:middle;
 5696: }
 5697: 
 5698: div.LC_feedback_link a {
 5699:   text-decoration: none;
 5700: }
 5701: 
 5702: div.LC_comblock {
 5703:   display:inline;
 5704:   color:$font;
 5705:   font-size:90%;
 5706: }
 5707: 
 5708: div.LC_feedback_link div.LC_comblock {
 5709:   padding-left:5px;
 5710: }
 5711: 
 5712: div.LC_feedback_link div.LC_comblock a {
 5713:   color:$font;
 5714: }
 5715: 
 5716: span.LC_feedback_link {
 5717:   /* background: $feedback_link_bg; */
 5718:   font-size: larger;
 5719: }
 5720: 
 5721: span.LC_message_link {
 5722:   /* background: $feedback_link_bg; */
 5723:   font-size: larger;
 5724:   position: absolute;
 5725:   right: 1em;
 5726: }
 5727: 
 5728: table.LC_prior_tries {
 5729:   border: 1px solid #000000;
 5730:   border-collapse: separate;
 5731:   border-spacing: 1px;
 5732: }
 5733: 
 5734: table.LC_prior_tries td {
 5735:   padding: 2px;
 5736: }
 5737: 
 5738: .LC_answer_correct {
 5739:   background: lightgreen;
 5740:   color: darkgreen;
 5741:   padding: 6px;
 5742: }
 5743: 
 5744: .LC_answer_charged_try {
 5745:   background: #FFAAAA;
 5746:   color: darkred;
 5747:   padding: 6px;
 5748: }
 5749: 
 5750: .LC_answer_not_charged_try,
 5751: .LC_answer_no_grade,
 5752: .LC_answer_late {
 5753:   background: lightyellow;
 5754:   color: black;
 5755:   padding: 6px;
 5756: }
 5757: 
 5758: .LC_answer_previous {
 5759:   background: lightblue;
 5760:   color: darkblue;
 5761:   padding: 6px;
 5762: }
 5763: 
 5764: .LC_answer_no_message {
 5765:   background: #FFFFFF;
 5766:   color: black;
 5767:   padding: 6px;
 5768: }
 5769: 
 5770: .LC_answer_unknown {
 5771:   background: orange;
 5772:   color: black;
 5773:   padding: 6px;
 5774: }
 5775: 
 5776: span.LC_prior_numerical,
 5777: span.LC_prior_string,
 5778: span.LC_prior_custom,
 5779: span.LC_prior_reaction,
 5780: span.LC_prior_math {
 5781:   font-family: $mono;
 5782:   white-space: pre;
 5783: }
 5784: 
 5785: span.LC_prior_string {
 5786:   font-family: $mono;
 5787:   white-space: pre;
 5788: }
 5789: 
 5790: table.LC_prior_option {
 5791:   width: 100%;
 5792:   border-collapse: collapse;
 5793: }
 5794: 
 5795: table.LC_prior_rank,
 5796: table.LC_prior_match {
 5797:   border-collapse: collapse;
 5798: }
 5799: 
 5800: table.LC_prior_option tr td,
 5801: table.LC_prior_rank tr td,
 5802: table.LC_prior_match tr td {
 5803:   border: 1px solid #000000;
 5804: }
 5805: 
 5806: .LC_nobreak {
 5807:   white-space: nowrap;
 5808: }
 5809: 
 5810: span.LC_cusr_emph {
 5811:   font-style: italic;
 5812: }
 5813: 
 5814: span.LC_cusr_subheading {
 5815:   font-weight: normal;
 5816:   font-size: 85%;
 5817: }
 5818: 
 5819: div.LC_docs_entry_move {
 5820:   border: 1px solid #BBBBBB;
 5821:   background: #DDDDDD;
 5822:   width: 22px;
 5823:   padding: 1px;
 5824:   margin: 0;
 5825: }
 5826: 
 5827: table.LC_data_table tr > td.LC_docs_entry_commands,
 5828: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5829:   background: #DDDDDD;
 5830:   font-size: x-small;
 5831: }
 5832: 
 5833: .LC_docs_entry_parameter {
 5834:   white-space: nowrap;
 5835: }
 5836: 
 5837: .LC_docs_copy {
 5838:   color: #000099;
 5839: }
 5840: 
 5841: .LC_docs_cut {
 5842:   color: #550044;
 5843: }
 5844: 
 5845: .LC_docs_rename {
 5846:   color: #009900;
 5847: }
 5848: 
 5849: .LC_docs_remove {
 5850:   color: #990000;
 5851: }
 5852: 
 5853: .LC_docs_reinit_warn,
 5854: .LC_docs_ext_edit {
 5855:   font-size: x-small;
 5856: }
 5857: 
 5858: table.LC_docs_adddocs td,
 5859: table.LC_docs_adddocs th {
 5860:   border: 1px solid #BBBBBB;
 5861:   padding: 4px;
 5862:   background: #DDDDDD;
 5863: }
 5864: 
 5865: table.LC_sty_begin {
 5866:   background: #BBFFBB;
 5867: }
 5868: 
 5869: table.LC_sty_end {
 5870:   background: #FFBBBB;
 5871: }
 5872: 
 5873: table.LC_double_column {
 5874:   border-width: 0;
 5875:   border-collapse: collapse;
 5876:   width: 100%;
 5877:   padding: 2px;
 5878: }
 5879: 
 5880: table.LC_double_column tr td.LC_left_col {
 5881:   top: 2px;
 5882:   left: 2px;
 5883:   width: 47%;
 5884:   vertical-align: top;
 5885: }
 5886: 
 5887: table.LC_double_column tr td.LC_right_col {
 5888:   top: 2px;
 5889:   right: 2px;
 5890:   width: 47%;
 5891:   vertical-align: top;
 5892: }
 5893: 
 5894: div.LC_left_float {
 5895:   float: left;
 5896:   padding-right: 5%;
 5897:   padding-bottom: 4px;
 5898: }
 5899: 
 5900: div.LC_clear_float_header {
 5901:   padding-bottom: 2px;
 5902: }
 5903: 
 5904: div.LC_clear_float_footer {
 5905:   padding-top: 10px;
 5906:   clear: both;
 5907: }
 5908: 
 5909: div.LC_grade_show_user {
 5910: /*  border-left: 5px solid $sidebg; */
 5911:   border-top: 5px solid #000000;
 5912:   margin: 50px 0 0 0;
 5913:   padding: 15px 0 5px 10px;
 5914: }
 5915: 
 5916: div.LC_grade_show_user_odd_row {
 5917: /*  border-left: 5px solid #000000; */
 5918: }
 5919: 
 5920: div.LC_grade_show_user div.LC_Box {
 5921:   margin-right: 50px;
 5922: }
 5923: 
 5924: div.LC_grade_submissions,
 5925: div.LC_grade_message_center,
 5926: div.LC_grade_info_links {
 5927:   margin: 5px;
 5928:   width: 99%;
 5929:   background: #FFFFFF;
 5930: }
 5931: 
 5932: div.LC_grade_submissions_header,
 5933: div.LC_grade_message_center_header {
 5934:   font-weight: bold;
 5935:   font-size: large;
 5936: }
 5937: 
 5938: div.LC_grade_submissions_body,
 5939: div.LC_grade_message_center_body {
 5940:   border: 1px solid black;
 5941:   width: 99%;
 5942:   background: #FFFFFF;
 5943: }
 5944: 
 5945: table.LC_scantron_action {
 5946:   width: 100%;
 5947: }
 5948: 
 5949: table.LC_scantron_action tr th {
 5950:   font-weight:bold;
 5951:   font-style:normal;
 5952: }
 5953: 
 5954: .LC_edit_problem_header,
 5955: div.LC_edit_problem_footer {
 5956:   font-weight: normal;
 5957:   font-size:  medium;
 5958:   margin: 2px;
 5959: }
 5960: 
 5961: div.LC_edit_problem_header,
 5962: div.LC_edit_problem_header div,
 5963: div.LC_edit_problem_footer,
 5964: div.LC_edit_problem_footer div,
 5965: div.LC_edit_problem_editxml_header,
 5966: div.LC_edit_problem_editxml_header div {
 5967:   margin-top: 5px;
 5968: }
 5969: 
 5970: div.LC_edit_problem_header_title {
 5971:   font-weight: bold;
 5972:   font-size: larger;
 5973:   background: $tabbg;
 5974:   padding: 3px;
 5975: }
 5976: 
 5977: table.LC_edit_problem_header_title {
 5978:   width: 100%;
 5979:   background: $tabbg;
 5980: }
 5981: 
 5982: div.LC_edit_problem_discards {
 5983:   float: left;
 5984:   padding-bottom: 5px;
 5985: }
 5986: 
 5987: div.LC_edit_problem_saves {
 5988:   float: right;
 5989:   padding-bottom: 5px;
 5990: }
 5991: 
 5992: img.stift {
 5993:   border-width: 0;
 5994:   vertical-align: middle;
 5995: }
 5996: 
 5997: table td.LC_mainmenu_col_fieldset {
 5998:   vertical-align: top;
 5999: }
 6000: 
 6001: div.LC_createcourse {
 6002:   margin: 10px 10px 10px 10px;
 6003: }
 6004: 
 6005: .LC_dccid {
 6006:   margin: 0.2em 0 0 0;
 6007:   padding: 0;
 6008:   font-size: 90%;
 6009:   display:none;
 6010: }
 6011: 
 6012: a:hover,
 6013: ol.LC_primary_menu a:hover,
 6014: ol#LC_MenuBreadcrumbs a:hover,
 6015: ol#LC_PathBreadcrumbs a:hover,
 6016: ul#LC_secondary_menu a:hover,
 6017: .LC_FormSectionClearButton input:hover
 6018: ul.LC_TabContent   li:hover a {
 6019:   color:$button_hover;
 6020:   text-decoration:none;
 6021: }
 6022: 
 6023: h1 {
 6024:   padding: 0;
 6025:   line-height:130%;
 6026: }
 6027: 
 6028: h2,
 6029: h3,
 6030: h4,
 6031: h5,
 6032: h6 {
 6033:   margin: 5px 0 5px 0;
 6034:   padding: 0;
 6035:   line-height:130%;
 6036: }
 6037: 
 6038: .LC_hcell {
 6039:   padding:3px 15px 3px 15px;
 6040:   margin: 0;
 6041:   background-color:$tabbg;
 6042:   color:$fontmenu;
 6043:   border-bottom:solid 1px $lg_border_color;
 6044: }
 6045: 
 6046: .LC_Box > .LC_hcell {
 6047:   margin: 0 -10px 10px -10px;
 6048: }
 6049: 
 6050: .LC_noBorder {
 6051:   border: 0;
 6052: }
 6053: 
 6054: .LC_FormSectionClearButton input {
 6055:   background-color:transparent;
 6056:   border: none;
 6057:   cursor:pointer;
 6058:   text-decoration:underline;
 6059: }
 6060: 
 6061: .LC_help_open_topic {
 6062:   color: #FFFFFF;
 6063:   background-color: #EEEEFF;
 6064:   margin: 1px;
 6065:   padding: 4px;
 6066:   border: 1px solid #000033;
 6067:   white-space: nowrap;
 6068:   /* vertical-align: middle; */
 6069: }
 6070: 
 6071: dl,
 6072: ul,
 6073: div,
 6074: fieldset {
 6075:   margin: 10px 10px 10px 0;
 6076:   /* overflow: hidden; */
 6077: }
 6078: 
 6079: fieldset > legend {
 6080:   font-weight: bold;
 6081:   padding: 0 5px 0 5px;
 6082: }
 6083: 
 6084: #LC_nav_bar {
 6085:   float: left;
 6086:   background-color: $pgbg_or_bgcolor;
 6087:   margin: 0 0 2px 0;
 6088: }
 6089: 
 6090: #LC_realm {
 6091:   margin: 0.2em 0 0 0;
 6092:   padding: 0;
 6093:   font-weight: bold;
 6094:   text-align: center;
 6095:   background-color: $pgbg_or_bgcolor;
 6096: }
 6097: 
 6098: #LC_nav_bar em {
 6099:   font-weight: bold;
 6100:   font-style: normal;
 6101: }
 6102: 
 6103: ol.LC_primary_menu {
 6104:   float: right;
 6105:   margin: 0;
 6106:   background-color: $pgbg_or_bgcolor;
 6107: }
 6108: 
 6109: ol#LC_PathBreadcrumbs {
 6110:   margin: 0;
 6111: }
 6112: 
 6113: ol.LC_primary_menu li {
 6114:   display: inline;
 6115:   padding: 5px 5px 0 10px;
 6116:   vertical-align: top;
 6117: }
 6118: 
 6119: ol.LC_primary_menu li img {
 6120:   vertical-align: bottom;
 6121:   height: 1.1em;
 6122: }
 6123: 
 6124: ol.LC_primary_menu a {
 6125:   color: RGB(80, 80, 80);
 6126:   text-decoration: none;
 6127: }
 6128: 
 6129: ol.LC_primary_menu a.LC_new_message {
 6130:   font-weight:bold;
 6131:   color: darkred;
 6132: }
 6133: 
 6134: ol.LC_docs_parameters {
 6135:   margin-left: 0;
 6136:   padding: 0;
 6137:   list-style: none;
 6138: }
 6139: 
 6140: ol.LC_docs_parameters li {
 6141:   margin: 0;
 6142:   padding-right: 20px;
 6143:   display: inline;
 6144: }
 6145: 
 6146: ol.LC_docs_parameters li:before {
 6147:   content: "\\002022 \\0020";
 6148: }
 6149: 
 6150: li.LC_docs_parameters_title {
 6151:   font-weight: bold;
 6152: }
 6153: 
 6154: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6155:   content: "";
 6156: }
 6157: 
 6158: ul#LC_secondary_menu {
 6159:   clear: both;
 6160:   color: $fontmenu;
 6161:   background: $tabbg;
 6162:   list-style: none;
 6163:   padding: 0;
 6164:   margin: 0;
 6165:   width: 100%;
 6166:   text-align: left;
 6167: }
 6168: 
 6169: ul#LC_secondary_menu li {
 6170:   font-weight: bold;
 6171:   line-height: 1.8em;
 6172:   padding: 0 0.8em;
 6173:   border-right: 1px solid black;
 6174:   display: inline;
 6175:   vertical-align: middle;
 6176: }
 6177: 
 6178: ul.LC_TabContent {
 6179:   display:block;
 6180:   background: $sidebg;
 6181:   border-bottom: solid 1px $lg_border_color;
 6182:   list-style:none;
 6183:   margin: 0 -10px;
 6184:   padding: 0;
 6185: }
 6186: 
 6187: ul.LC_TabContent li,
 6188: ul.LC_TabContentBigger li {
 6189:   float:left;
 6190: }
 6191: 
 6192: ul#LC_secondary_menu li a {
 6193:   color: $fontmenu;
 6194:   text-decoration: none;
 6195: }
 6196: 
 6197: ul.LC_TabContent {
 6198:   min-height:20px;
 6199: }
 6200: 
 6201: ul.LC_TabContent li {
 6202:   vertical-align:middle;
 6203:   padding: 0 16px 0 10px;
 6204:   background-color:$tabbg;
 6205:   border-bottom:solid 1px $lg_border_color;
 6206:   border-right: solid 1px $font;
 6207: }
 6208: 
 6209: ul.LC_TabContent .right {
 6210:   float:right;
 6211: }
 6212: 
 6213: ul.LC_TabContent li a,
 6214: ul.LC_TabContent li {
 6215:   color:rgb(47,47,47);
 6216:   text-decoration:none;
 6217:   font-size:95%;
 6218:   font-weight:bold;
 6219:   min-height:20px;
 6220: }
 6221: 
 6222: ul.LC_TabContent li a:hover,
 6223: ul.LC_TabContent li a:focus {
 6224:   color: $button_hover;
 6225:   background:none;
 6226:   outline:none;
 6227: }
 6228: 
 6229: ul.LC_TabContent li:hover {
 6230:   color: $button_hover;
 6231:   cursor:pointer;
 6232: }
 6233: 
 6234: ul.LC_TabContent li.active {
 6235:   color: $font;
 6236:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6237:   border-bottom:solid 1px #FFFFFF;
 6238:   cursor: default;
 6239: }
 6240: 
 6241: ul.LC_TabContent li.active a {
 6242:   color:$font;
 6243:   background:#FFFFFF;
 6244:   outline: none;
 6245: }
 6246: #maincoursedoc {
 6247:   clear:both;
 6248: }
 6249: 
 6250: ul.LC_TabContentBigger {
 6251:   display:block;
 6252:   list-style:none;
 6253:   padding: 0;
 6254: }
 6255: 
 6256: ul.LC_TabContentBigger li {
 6257:   vertical-align:bottom;
 6258:   height: 30px;
 6259:   font-size:110%;
 6260:   font-weight:bold;
 6261:   color: #737373;
 6262: }
 6263: 
 6264: ul.LC_TabContentBigger li.active {
 6265:   position: relative;
 6266:   top: 1px;
 6267: }
 6268: 
 6269: ul.LC_TabContentBigger li a {
 6270:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6271:   height: 30px;
 6272:   line-height: 30px;
 6273:   text-align: center;
 6274:   display: block;
 6275:   text-decoration: none;
 6276:   outline: none;  
 6277: }
 6278: 
 6279: ul.LC_TabContentBigger li.active a {
 6280:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6281:   color:$font;
 6282: }
 6283: 
 6284: ul.LC_TabContentBigger li b {
 6285:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6286:   display: block;
 6287:   float: left;
 6288:   padding: 0 30px;
 6289:   border-bottom: 1px solid $lg_border_color;
 6290: }
 6291: 
 6292: ul.LC_TabContentBigger li:hover b {
 6293:   color:$button_hover;
 6294: }
 6295: 
 6296: ul.LC_TabContentBigger li.active b {
 6297:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6298:   color:$font;
 6299:   border: 0;
 6300: }
 6301: 
 6302: 
 6303: ul.LC_CourseBreadcrumbs {
 6304:   background: $sidebg;
 6305:   line-height: 32px;
 6306:   padding-left: 10px;
 6307:   margin: 0 0 10px 0;
 6308:   list-style-position: inside;
 6309: 
 6310: }
 6311: 
 6312: ol#LC_MenuBreadcrumbs,
 6313: ol#LC_PathBreadcrumbs {
 6314:   padding-left: 10px;
 6315:   margin: 0;
 6316:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6317: }
 6318: 
 6319: ol#LC_MenuBreadcrumbs li,
 6320: ol#LC_PathBreadcrumbs li,
 6321: ul.LC_CourseBreadcrumbs li {
 6322:   display: inline;
 6323:   white-space: normal;  
 6324: }
 6325: 
 6326: ol#LC_MenuBreadcrumbs li a,
 6327: ul.LC_CourseBreadcrumbs li a {
 6328:   text-decoration: none;
 6329:   font-size:90%;
 6330: }
 6331: 
 6332: ol#LC_MenuBreadcrumbs h1 {
 6333:   display: inline;
 6334:   font-size: 90%;
 6335:   line-height: 2.5em;
 6336:   margin: 0;
 6337:   padding: 0;
 6338: }
 6339: 
 6340: ol#LC_PathBreadcrumbs li a {
 6341:   text-decoration:none;
 6342:   font-size:100%;
 6343:   font-weight:bold;
 6344: }
 6345: 
 6346: .LC_Box {
 6347:   border: solid 1px $lg_border_color;
 6348:   padding: 0 10px 10px 10px;
 6349: }
 6350: 
 6351: .LC_AboutMe_Image {
 6352:   float:left;
 6353:   margin-right:10px;
 6354: }
 6355: 
 6356: .LC_Clear_AboutMe_Image {
 6357:   clear:left;
 6358: }
 6359: 
 6360: dl.LC_ListStyleClean dt {
 6361:   padding-right: 5px;
 6362:   display: table-header-group;
 6363: }
 6364: 
 6365: dl.LC_ListStyleClean dd {
 6366:   display: table-row;
 6367: }
 6368: 
 6369: .LC_ListStyleClean,
 6370: .LC_ListStyleSimple,
 6371: .LC_ListStyleNormal,
 6372: .LC_ListStyleSpecial {
 6373:   /* display:block; */
 6374:   list-style-position: inside;
 6375:   list-style-type: none;
 6376:   overflow: hidden;
 6377:   padding: 0;
 6378: }
 6379: 
 6380: .LC_ListStyleSimple li,
 6381: .LC_ListStyleSimple dd,
 6382: .LC_ListStyleNormal li,
 6383: .LC_ListStyleNormal dd,
 6384: .LC_ListStyleSpecial li,
 6385: .LC_ListStyleSpecial dd {
 6386:   margin: 0;
 6387:   padding: 5px 5px 5px 10px;
 6388:   clear: both;
 6389: }
 6390: 
 6391: .LC_ListStyleClean li,
 6392: .LC_ListStyleClean dd {
 6393:   padding-top: 0;
 6394:   padding-bottom: 0;
 6395: }
 6396: 
 6397: .LC_ListStyleSimple dd,
 6398: .LC_ListStyleSimple li {
 6399:   border-bottom: solid 1px $lg_border_color;
 6400: }
 6401: 
 6402: .LC_ListStyleSpecial li,
 6403: .LC_ListStyleSpecial dd {
 6404:   list-style-type: none;
 6405:   background-color: RGB(220, 220, 220);
 6406:   margin-bottom: 4px;
 6407: }
 6408: 
 6409: table.LC_SimpleTable {
 6410:   margin:5px;
 6411:   border:solid 1px $lg_border_color;
 6412: }
 6413: 
 6414: table.LC_SimpleTable tr {
 6415:   padding: 0;
 6416:   border:solid 1px $lg_border_color;
 6417: }
 6418: 
 6419: table.LC_SimpleTable thead {
 6420:   background:rgb(220,220,220);
 6421: }
 6422: 
 6423: div.LC_columnSection {
 6424:   display: block;
 6425:   clear: both;
 6426:   overflow: hidden;
 6427:   margin: 0;
 6428: }
 6429: 
 6430: div.LC_columnSection>* {
 6431:   float: left;
 6432:   margin: 10px 20px 10px 0;
 6433:   overflow:hidden;
 6434: }
 6435: 
 6436: table em {
 6437:   font-weight: bold;
 6438:   font-style: normal;
 6439: }
 6440: 
 6441: table.LC_tableBrowseRes,
 6442: table.LC_tableOfContent {
 6443:   border:none;
 6444:   border-spacing: 1px;
 6445:   padding: 3px;
 6446:   background-color: #FFFFFF;
 6447:   font-size: 90%;
 6448: }
 6449: 
 6450: table.LC_tableOfContent {
 6451:   border-collapse: collapse;
 6452: }
 6453: 
 6454: table.LC_tableBrowseRes a,
 6455: table.LC_tableOfContent a {
 6456:   background-color: transparent;
 6457:   text-decoration: none;
 6458: }
 6459: 
 6460: table.LC_tableOfContent img {
 6461:   border: none;
 6462:   height: 1.3em;
 6463:   vertical-align: text-bottom;
 6464:   margin-right: 0.3em;
 6465: }
 6466: 
 6467: a#LC_content_toolbar_firsthomework {
 6468:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6469: }
 6470: 
 6471: a#LC_content_toolbar_everything {
 6472:   background-image:url(/res/adm/pages/show-all.gif);
 6473: }
 6474: 
 6475: a#LC_content_toolbar_uncompleted {
 6476:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6477: }
 6478: 
 6479: #LC_content_toolbar_clearbubbles {
 6480:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6481: }
 6482: 
 6483: a#LC_content_toolbar_changefolder {
 6484:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6485: }
 6486: 
 6487: a#LC_content_toolbar_changefolder_toggled {
 6488:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6489: }
 6490: 
 6491: ul#LC_toolbar li a:hover {
 6492:   background-position: bottom center;
 6493: }
 6494: 
 6495: ul#LC_toolbar {
 6496:   padding: 0;
 6497:   margin: 2px;
 6498:   list-style:none;
 6499:   position:relative;
 6500:   background-color:white;
 6501: }
 6502: 
 6503: ul#LC_toolbar li {
 6504:   border:1px solid white;
 6505:   padding: 0;
 6506:   margin: 0;
 6507:   float: left;
 6508:   display:inline;
 6509:   vertical-align:middle;
 6510: }
 6511: 
 6512: 
 6513: a.LC_toolbarItem {
 6514:   display:block;
 6515:   padding: 0;
 6516:   margin: 0;
 6517:   height: 32px;
 6518:   width: 32px;
 6519:   color:white;
 6520:   border: none;
 6521:   background-repeat:no-repeat;
 6522:   background-color:transparent;
 6523: }
 6524: 
 6525: ul.LC_funclist {
 6526:     margin: 0;
 6527:     padding: 0.5em 1em 0.5em 0;
 6528: }
 6529: 
 6530: ul.LC_funclist > li:first-child {
 6531:     font-weight:bold; 
 6532:     margin-left:0.8em;
 6533: }
 6534: 
 6535: ul.LC_funclist + ul.LC_funclist {
 6536:     /* 
 6537:        left border as a seperator if we have more than
 6538:        one list 
 6539:     */
 6540:     border-left: 1px solid $sidebg;
 6541:     /* 
 6542:        this hides the left border behind the border of the 
 6543:        outer box if element is wrapped to the next 'line' 
 6544:     */
 6545:     margin-left: -1px;
 6546: }
 6547: 
 6548: ul.LC_funclist li {
 6549:   display: inline;
 6550:   white-space: nowrap;
 6551:   margin: 0 0 0 25px;
 6552:   line-height: 150%;
 6553: }
 6554: 
 6555: .LC_hidden {
 6556:   display: none;
 6557: }
 6558: 
 6559: END
 6560: }
 6561: 
 6562: =pod
 6563: 
 6564: =item * &headtag()
 6565: 
 6566: Returns a uniform footer for LON-CAPA web pages.
 6567: 
 6568: Inputs: $title - optional title for the head
 6569:         $head_extra - optional extra HTML to put inside the <head>
 6570:         $args - optional arguments
 6571:             force_register - if is true call registerurl so the remote is 
 6572:                              informed
 6573:             redirect       -> array ref of
 6574:                                    1- seconds before redirect occurs
 6575:                                    2- url to redirect to
 6576:                                    3- whether the side effect should occur
 6577:                            (side effect of setting 
 6578:                                $env{'internal.head.redirect'} to the url 
 6579:                                redirected too)
 6580:             domain         -> force to color decorate a page for a specific
 6581:                                domain
 6582:             function       -> force usage of a specific rolish color scheme
 6583:             bgcolor        -> override the default page bgcolor
 6584:             no_auto_mt_title
 6585:                            -> prevent &mt()ing the title arg
 6586: 
 6587: =cut
 6588: 
 6589: sub headtag {
 6590:     my ($title,$head_extra,$args) = @_;
 6591:     
 6592:     my $function = $args->{'function'} || &get_users_function();
 6593:     my $domain   = $args->{'domain'}   || &determinedomain();
 6594:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6595:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6596: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6597: 		   #time(),
 6598: 		   $env{'environment.color.timestamp'},
 6599: 		   $function,$domain,$bgcolor);
 6600: 
 6601:     $url = '/adm/css/'.&escape($url).'.css';
 6602: 
 6603:     my $result =
 6604: 	'<head>'.
 6605: 	&font_settings();
 6606: 
 6607:     if (!$args->{'frameset'}) {
 6608: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6609:     }
 6610:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 6611:         $result .= Apache::lonxml::display_title();
 6612:     }
 6613:     if (!$args->{'no_nav_bar'} 
 6614: 	&& !$args->{'only_body'}
 6615: 	&& !$args->{'frameset'}) {
 6616: 	$result .= &help_menu_js();
 6617:     }
 6618: 
 6619:     if (ref($args->{'redirect'})) {
 6620: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6621: 	$url = &Apache::lonenc::check_encrypt($url);
 6622: 	if (!$inhibit_continue) {
 6623: 	    $env{'internal.head.redirect'} = $url;
 6624: 	}
 6625: 	$result.=<<ADDMETA
 6626: <meta http-equiv="pragma" content="no-cache" />
 6627: <meta http-equiv="Refresh" content="$time; url=$url" />
 6628: ADDMETA
 6629:     }
 6630:     if (!defined($title)) {
 6631: 	$title = 'The LearningOnline Network with CAPA';
 6632:     }
 6633:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6634:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6635: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6636: 	.$head_extra;
 6637:     return $result.'</head>';
 6638: }
 6639: 
 6640: =pod
 6641: 
 6642: =item * &font_settings()
 6643: 
 6644: Returns neccessary <meta> to set the proper encoding
 6645: 
 6646: Inputs: none
 6647: 
 6648: =cut
 6649: 
 6650: sub font_settings {
 6651:     my $headerstring='';
 6652:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6653: 	$headerstring.=
 6654: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6655:     }
 6656:     return $headerstring;
 6657: }
 6658: 
 6659: =pod
 6660: 
 6661: =item * &xml_begin()
 6662: 
 6663: Returns the needed doctype and <html>
 6664: 
 6665: Inputs: none
 6666: 
 6667: =cut
 6668: 
 6669: sub xml_begin {
 6670:     my $output='';
 6671: 
 6672:     if ($env{'browser.mathml'}) {
 6673: 	$output='<?xml version="1.0"?>'
 6674:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6675: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6676:             
 6677: #	    .'<!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">] >'
 6678: 	    .'<!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">'
 6679:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6680: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6681:     } else {
 6682: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6683:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6684:     }
 6685:     return $output;
 6686: }
 6687: 
 6688: =pod
 6689: 
 6690: =item * &start_page()
 6691: 
 6692: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6693: 
 6694: Inputs:
 6695: 
 6696: =over 4
 6697: 
 6698: $title - optional title for the page
 6699: 
 6700: $head_extra - optional extra HTML to incude inside the <head>
 6701: 
 6702: $args - additional optional args supported are:
 6703: 
 6704: =over 8
 6705: 
 6706:              only_body      -> is true will set &bodytag() onlybodytag
 6707:                                     arg on
 6708:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6709:              add_entries    -> additional attributes to add to the  <body>
 6710:              domain         -> force to color decorate a page for a 
 6711:                                     specific domain
 6712:              function       -> force usage of a specific rolish color
 6713:                                     scheme
 6714:              redirect       -> see &headtag()
 6715:              bgcolor        -> override the default page bg color
 6716:              js_ready       -> return a string ready for being used in 
 6717:                                     a javascript writeln
 6718:              html_encode    -> return a string ready for being used in 
 6719:                                     a html attribute
 6720:              force_register -> if is true will turn on the &bodytag()
 6721:                                     $forcereg arg
 6722:              frameset       -> if true will start with a <frameset>
 6723:                                     rather than <body>
 6724:              skip_phases    -> hash ref of 
 6725:                                     head -> skip the <html><head> generation
 6726:                                     body -> skip all <body> generation
 6727:              no_auto_mt_title -> prevent &mt()ing the title arg
 6728:              inherit_jsmath -> when creating popup window in a page,
 6729:                                     should it have jsmath forced on by the
 6730:                                     current page
 6731:              bread_crumbs ->             Array containing breadcrumbs
 6732:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 6733: 
 6734: =back
 6735: 
 6736: =back
 6737: 
 6738: =cut
 6739: 
 6740: sub start_page {
 6741:     my ($title,$head_extra,$args) = @_;
 6742:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6743: #SD
 6744: #I don't see why we copy certain elements of %$args to %head_args
 6745: #head args is passed to headtag() and this routine only reads those
 6746: #keys that are needed. There doesn't happen any writes or any processing
 6747: #of other keys.
 6748: #proposal: just pass $args to headtag instead of \%head_args and delete 
 6749: #marked lines
 6750: #<- MARK
 6751:     my %head_args;
 6752:     foreach my $arg ('redirect','force_register','domain','function',
 6753: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6754: 		     'no_auto_mt_title') {
 6755: 	if (defined($args->{$arg})) {
 6756: 	    $head_args{$arg} = $args->{$arg};
 6757: 	}
 6758:     }
 6759: #MARK ->
 6760: 
 6761:     $env{'internal.start_page'}++;
 6762:     my $result;
 6763: 
 6764:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6765:         $result .= 
 6766:                   &xml_begin() . &headtag($title,$head_extra,\%head_args);
 6767: #replace prev line by
 6768: #                 &xml_begin() . &headtag($title, $head_extra, $args);
 6769:     }
 6770:     
 6771:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6772: 	if ($args->{'frameset'}) {
 6773: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6774: 						$args->{'add_entries'});
 6775: 	    $result .= "\n<frameset $attr_string>\n";
 6776:         } else {
 6777:             $result .=
 6778:                 &bodytag($title, 
 6779:                          $args->{'function'},       $args->{'add_entries'},
 6780:                          $args->{'only_body'},      $args->{'domain'},
 6781:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6782:                          $args->{'bgcolor'},        $args);
 6783:         }
 6784:     }
 6785: 
 6786:     if ($args->{'js_ready'}) {
 6787: 		$result = &js_ready($result);
 6788:     }
 6789:     if ($args->{'html_encode'}) {
 6790: 		$result = &html_encode($result);
 6791:     }
 6792: 
 6793:     # Preparation for new and consistent functionlist at top of screen
 6794:     # if ($args->{'functionlist'}) {
 6795:     #            $result .= &build_functionlist();
 6796:     #}
 6797: 
 6798:     # Don't add anything more if only_body wanted or in const space
 6799:     return $result if    $args->{'only_body'} 
 6800:                       || $env{'request.state'} eq 'construct';
 6801: 
 6802:     #Breadcrumbs
 6803:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6804: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6805: 		#if any br links exists, add them to the breadcrumbs
 6806: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6807: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6808: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6809: 			}
 6810: 		}
 6811: 
 6812: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6813: 		if(exists($args->{'bread_crumbs_component'})){
 6814: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6815: 		}else{
 6816: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6817: 		}
 6818:     }
 6819:     return $result;
 6820: }
 6821: 
 6822: sub end_page {
 6823:     my ($args) = @_;
 6824:     $env{'internal.end_page'}++;
 6825:     my $result;
 6826:     if ($args->{'discussion'}) {
 6827: 	my ($target,$parser);
 6828: 	if (ref($args->{'discussion'})) {
 6829: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6830: 				$args->{'discussion'}{'parser'});
 6831: 	}
 6832: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6833:     }
 6834: 
 6835:     if ($args->{'frameset'}) {
 6836: 	$result .= '</frameset>';
 6837:     } else {
 6838: 	$result .= &endbodytag($args);
 6839:     }
 6840:     $result .= "\n</html>";
 6841: 
 6842:     if ($args->{'js_ready'}) {
 6843: 	$result = &js_ready($result);
 6844:     }
 6845: 
 6846:     if ($args->{'html_encode'}) {
 6847: 	$result = &html_encode($result);
 6848:     }
 6849: 
 6850:     return $result;
 6851: }
 6852: 
 6853: sub html_encode {
 6854:     my ($result) = @_;
 6855: 
 6856:     $result = &HTML::Entities::encode($result,'<>&"');
 6857:     
 6858:     return $result;
 6859: }
 6860: sub js_ready {
 6861:     my ($result) = @_;
 6862: 
 6863:     $result =~ s/[\n\r]/ /xmsg;
 6864:     $result =~ s/\\/\\\\/xmsg;
 6865:     $result =~ s/'/\\'/xmsg;
 6866:     $result =~ s{</}{<\\/}xmsg;
 6867:     
 6868:     return $result;
 6869: }
 6870: 
 6871: sub validate_page {
 6872:     if (  exists($env{'internal.start_page'})
 6873: 	  &&     $env{'internal.start_page'} > 1) {
 6874: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6875: 				 $env{'internal.start_page'}.' '.
 6876: 				 $ENV{'request.filename'});
 6877:     }
 6878:     if (  exists($env{'internal.end_page'})
 6879: 	  &&     $env{'internal.end_page'} > 1) {
 6880: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6881: 				 $env{'internal.end_page'}.' '.
 6882: 				 $env{'request.filename'});
 6883:     }
 6884:     if (     exists($env{'internal.start_page'})
 6885: 	&& ! exists($env{'internal.end_page'})) {
 6886: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6887: 				 $env{'request.filename'});
 6888:     }
 6889:     if (   ! exists($env{'internal.start_page'})
 6890: 	&&   exists($env{'internal.end_page'})) {
 6891: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6892: 				 $env{'request.filename'});
 6893:     }
 6894: }
 6895: 
 6896: 
 6897: sub start_scrollbox {
 6898:     my ($outerwidth,$width,$height)=@_;
 6899:     unless ($outerwidth) { $outerwidth='520px'; }
 6900:     unless ($width) { $width='500px'; }
 6901:     unless ($height) { $height='200px'; }
 6902:     return "<table style='width: $outerwidth; border: 1px solid black;'><tr><td style='width: $width;' bgcolor='#FFFFFF'><div style='overflow:auto; width:$width; height: $height;'>";
 6903: }
 6904: 
 6905: sub end_scrollbox {
 6906:     return '</td></tr></table>';
 6907: }
 6908: 
 6909: sub simple_error_page {
 6910:     my ($r,$title,$msg) = @_;
 6911:     my $page =
 6912: 	&Apache::loncommon::start_page($title).
 6913: 	&mt($msg).
 6914: 	&Apache::loncommon::end_page();
 6915:     if (ref($r)) {
 6916: 	$r->print($page);
 6917: 	return;
 6918:     }
 6919:     return $page;
 6920: }
 6921: 
 6922: {
 6923:     my @row_count;
 6924: 
 6925:     sub start_data_table_count {
 6926:         unshift(@row_count, 0);
 6927:         return;
 6928:     }
 6929: 
 6930:     sub end_data_table_count {
 6931:         shift(@row_count);
 6932:         return;
 6933:     }
 6934: 
 6935:     sub start_data_table {
 6936: 	my ($add_class) = @_;
 6937: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6938: 	&start_data_table_count();
 6939: 	return '<table class="'.$css_class.'">'."\n";
 6940:     }
 6941: 
 6942:     sub end_data_table {
 6943: 	&end_data_table_count();
 6944: 	return '</table>'."\n";;
 6945:     }
 6946: 
 6947:     sub start_data_table_row {
 6948: 	my ($add_class, $id) = @_;
 6949: 	$row_count[0]++;
 6950: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6951: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6952:         $id = (' id="'.$id.'"') unless ($id eq '');
 6953:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 6954:     }
 6955:     
 6956:     sub continue_data_table_row {
 6957: 	my ($add_class, $id) = @_;
 6958: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6959: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6960:         $id = (' id="'.$id.'"') unless ($id eq '');
 6961:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 6962:     }
 6963: 
 6964:     sub end_data_table_row {
 6965: 	return '</tr>'."\n";;
 6966:     }
 6967: 
 6968:     sub start_data_table_empty_row {
 6969: #	$row_count[0]++;
 6970: 	return  '<tr class="LC_empty_row" >'."\n";;
 6971:     }
 6972: 
 6973:     sub end_data_table_empty_row {
 6974: 	return '</tr>'."\n";;
 6975:     }
 6976: 
 6977:     sub start_data_table_header_row {
 6978: 	return  '<tr class="LC_header_row">'."\n";;
 6979:     }
 6980: 
 6981:     sub end_data_table_header_row {
 6982: 	return '</tr>'."\n";;
 6983:     }
 6984: 
 6985:     sub data_table_caption {
 6986:         my $caption = shift;
 6987:         return "<caption class=\"LC_caption\">$caption</caption>";
 6988:     }
 6989: }
 6990: 
 6991: =pod
 6992: 
 6993: =item * &inhibit_menu_check($arg)
 6994: 
 6995: Checks for a inhibitmenu state and generates output to preserve it
 6996: 
 6997: Inputs:         $arg - can be any of
 6998:                      - undef - in which case the return value is a string 
 6999:                                to add  into arguments list of a uri
 7000:                      - 'input' - in which case the return value is a HTML
 7001:                                  <form> <input> field of type hidden to
 7002:                                  preserve the value
 7003:                      - a url - in which case the return value is the url with
 7004:                                the neccesary cgi args added to preserve the
 7005:                                inhibitmenu state
 7006:                      - a ref to a url - no return value, but the string is
 7007:                                         updated to include the neccessary cgi
 7008:                                         args to preserve the inhibitmenu state
 7009: 
 7010: =cut
 7011: 
 7012: sub inhibit_menu_check {
 7013:     my ($arg) = @_;
 7014:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7015:     if ($arg eq 'input') {
 7016: 	if ($env{'form.inhibitmenu'}) {
 7017: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7018: 	} else {
 7019: 	    return
 7020: 	}
 7021:     }
 7022:     if ($env{'form.inhibitmenu'}) {
 7023: 	if (ref($arg)) {
 7024: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7025: 	} elsif ($arg eq '') {
 7026: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7027: 	} else {
 7028: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7029: 	}
 7030:     }
 7031:     if (!ref($arg)) {
 7032: 	return $arg;
 7033:     }
 7034: }
 7035: 
 7036: ###############################################
 7037: 
 7038: =pod
 7039: 
 7040: =back
 7041: 
 7042: =head1 User Information Routines
 7043: 
 7044: =over 4
 7045: 
 7046: =item * &get_users_function()
 7047: 
 7048: Used by &bodytag to determine the current users primary role.
 7049: Returns either 'student','coordinator','admin', or 'author'.
 7050: 
 7051: =cut
 7052: 
 7053: ###############################################
 7054: sub get_users_function {
 7055:     my $function = 'norole';
 7056:     if ($env{'request.role'}=~/^(st)/) {
 7057:         $function='student';
 7058:     }
 7059:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7060:         $function='coordinator';
 7061:     }
 7062:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7063:         $function='admin';
 7064:     }
 7065:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7066:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 7067:         $function='author';
 7068:     }
 7069:     return $function;
 7070: }
 7071: 
 7072: ###############################################
 7073: 
 7074: =pod
 7075: 
 7076: =item * &show_course()
 7077: 
 7078: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7079: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7080: 
 7081: Inputs:
 7082: None
 7083: 
 7084: Outputs:
 7085: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7086: 
 7087: =cut
 7088: 
 7089: ###############################################
 7090: sub show_course {
 7091:     my $course = !$env{'user.adv'};
 7092:     if (!$env{'user.adv'}) {
 7093:         foreach my $env (keys(%env)) {
 7094:             next if ($env !~ m/^user\.priv\./);
 7095:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7096:                 $course = 0;
 7097:                 last;
 7098:             }
 7099:         }
 7100:     }
 7101:     return $course;
 7102: }
 7103: 
 7104: ###############################################
 7105: 
 7106: =pod
 7107: 
 7108: =item * &check_user_status()
 7109: 
 7110: Determines current status of supplied role for a
 7111: specific user. Roles can be active, previous or future.
 7112: 
 7113: Inputs: 
 7114: user's domain, user's username, course's domain,
 7115: course's number, optional section ID.
 7116: 
 7117: Outputs:
 7118: role status: active, previous or future. 
 7119: 
 7120: =cut
 7121: 
 7122: sub check_user_status {
 7123:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7124:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 7125:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
 7126:     my @uroles = keys %userinfo;
 7127:     my $srchstr;
 7128:     my $active_chk = 'none';
 7129:     my $now = time;
 7130:     if (@uroles > 0) {
 7131:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7132:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7133:         } else {
 7134:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7135:         }
 7136:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7137:             my $role_end = 0;
 7138:             my $role_start = 0;
 7139:             $active_chk = 'active';
 7140:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7141:                 $role_end = $1;
 7142:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7143:                     $role_start = $1;
 7144:                 }
 7145:             }
 7146:             if ($role_start > 0) {
 7147:                 if ($now < $role_start) {
 7148:                     $active_chk = 'future';
 7149:                 }
 7150:             }
 7151:             if ($role_end > 0) {
 7152:                 if ($now > $role_end) {
 7153:                     $active_chk = 'previous';
 7154:                 }
 7155:             }
 7156:         }
 7157:     }
 7158:     return $active_chk;
 7159: }
 7160: 
 7161: ###############################################
 7162: 
 7163: =pod
 7164: 
 7165: =item * &get_sections()
 7166: 
 7167: Determines all the sections for a course including
 7168: sections with students and sections containing other roles.
 7169: Incoming parameters: 
 7170: 
 7171: 1. domain
 7172: 2. course number 
 7173: 3. reference to array containing roles for which sections should 
 7174: be gathered (optional).
 7175: 4. reference to array containing status types for which sections 
 7176: should be gathered (optional).
 7177: 
 7178: If the third argument is undefined, sections are gathered for any role. 
 7179: If the fourth argument is undefined, sections are gathered for any status.
 7180: Permissible values are 'active' or 'future' or 'previous'.
 7181:  
 7182: Returns section hash (keys are section IDs, values are
 7183: number of users in each section), subject to the
 7184: optional roles filter, optional status filter 
 7185: 
 7186: =cut
 7187: 
 7188: ###############################################
 7189: sub get_sections {
 7190:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7191:     if (!defined($cdom) || !defined($cnum)) {
 7192:         my $cid =  $env{'request.course.id'};
 7193: 
 7194: 	return if (!defined($cid));
 7195: 
 7196:         $cdom = $env{'course.'.$cid.'.domain'};
 7197:         $cnum = $env{'course.'.$cid.'.num'};
 7198:     }
 7199: 
 7200:     my %sectioncount;
 7201:     my $now = time;
 7202: 
 7203:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7204: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7205: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7206: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7207:         my $start_index = &Apache::loncoursedata::CL_START();
 7208:         my $end_index = &Apache::loncoursedata::CL_END();
 7209:         my $status;
 7210: 	while (my ($student,$data) = each(%$classlist)) {
 7211: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7212: 				                     $data->[$status_index],
 7213:                                                      $data->[$start_index],
 7214:                                                      $data->[$end_index]);
 7215:             if ($stu_status eq 'Active') {
 7216:                 $status = 'active';
 7217:             } elsif ($end < $now) {
 7218:                 $status = 'previous';
 7219:             } elsif ($start > $now) {
 7220:                 $status = 'future';
 7221:             } 
 7222: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7223:                 if ((!defined($possible_status)) || (($status ne '') && 
 7224:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7225: 		    $sectioncount{$section}++;
 7226:                 }
 7227: 	    }
 7228: 	}
 7229:     }
 7230:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7231:     foreach my $user (sort(keys(%courseroles))) {
 7232: 	if ($user !~ /^(\w{2})/) { next; }
 7233: 	my ($role) = ($user =~ /^(\w{2})/);
 7234: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7235: 	my ($section,$status);
 7236: 	if ($role eq 'cr' &&
 7237: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7238: 	    $section=$1;
 7239: 	}
 7240: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7241: 	if (!defined($section) || $section eq '-1') { next; }
 7242:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7243:         if ($end == -1 && $start == -1) {
 7244:             next; #deleted role
 7245:         }
 7246:         if (!defined($possible_status)) { 
 7247:             $sectioncount{$section}++;
 7248:         } else {
 7249:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7250:                 $status = 'active';
 7251:             } elsif ($end < $now) {
 7252:                 $status = 'future';
 7253:             } elsif ($start > $now) {
 7254:                 $status = 'previous';
 7255:             }
 7256:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7257:                 $sectioncount{$section}++;
 7258:             }
 7259:         }
 7260:     }
 7261:     return %sectioncount;
 7262: }
 7263: 
 7264: ###############################################
 7265: 
 7266: =pod
 7267: 
 7268: =item * &get_course_users()
 7269: 
 7270: Retrieves usernames:domains for users in the specified course
 7271: with specific role(s), and access status. 
 7272: 
 7273: Incoming parameters:
 7274: 1. course domain
 7275: 2. course number
 7276: 3. access status: users must have - either active, 
 7277: previous, future, or all.
 7278: 4. reference to array of permissible roles
 7279: 5. reference to array of section restrictions (optional)
 7280: 6. reference to results object (hash of hashes).
 7281: 7. reference to optional userdata hash
 7282: 8. reference to optional statushash
 7283: 9. flag if privileged users (except those set to unhide in
 7284:    course settings) should be excluded    
 7285: Keys of top level results hash are roles.
 7286: Keys of inner hashes are username:domain, with 
 7287: values set to access type.
 7288: Optional userdata hash returns an array with arguments in the 
 7289: same order as loncoursedata::get_classlist() for student data.
 7290: 
 7291: Optional statushash returns
 7292: 
 7293: Entries for end, start, section and status are blank because
 7294: of the possibility of multiple values for non-student roles.
 7295: 
 7296: =cut
 7297: 
 7298: ###############################################
 7299: 
 7300: sub get_course_users {
 7301:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7302:     my %idx = ();
 7303:     my %seclists;
 7304: 
 7305:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7306:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7307:     $idx{end} = &Apache::loncoursedata::CL_END();
 7308:     $idx{start} = &Apache::loncoursedata::CL_START();
 7309:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7310:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7311:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7312:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7313: 
 7314:     if (grep(/^st$/,@{$roles})) {
 7315:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7316:         my $now = time;
 7317:         foreach my $student (keys(%{$classlist})) {
 7318:             my $match = 0;
 7319:             my $secmatch = 0;
 7320:             my $section = $$classlist{$student}[$idx{section}];
 7321:             my $status = $$classlist{$student}[$idx{status}];
 7322:             if ($section eq '') {
 7323:                 $section = 'none';
 7324:             }
 7325:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7326:                 if (grep(/^all$/,@{$sections})) {
 7327:                     $secmatch = 1;
 7328:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7329:                     if (grep(/^none$/,@{$sections})) {
 7330:                         $secmatch = 1;
 7331:                     }
 7332:                 } else {  
 7333: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7334: 		        $secmatch = 1;
 7335:                     }
 7336: 		}
 7337:                 if (!$secmatch) {
 7338:                     next;
 7339:                 }
 7340:             }
 7341:             if (defined($$types{'active'})) {
 7342:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7343:                     push(@{$$users{st}{$student}},'active');
 7344:                     $match = 1;
 7345:                 }
 7346:             }
 7347:             if (defined($$types{'previous'})) {
 7348:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7349:                     push(@{$$users{st}{$student}},'previous');
 7350:                     $match = 1;
 7351:                 }
 7352:             }
 7353:             if (defined($$types{'future'})) {
 7354:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7355:                     push(@{$$users{st}{$student}},'future');
 7356:                     $match = 1;
 7357:                 }
 7358:             }
 7359:             if ($match) {
 7360:                 push(@{$seclists{$student}},$section);
 7361:                 if (ref($userdata) eq 'HASH') {
 7362:                     $$userdata{$student} = $$classlist{$student};
 7363:                 }
 7364:                 if (ref($statushash) eq 'HASH') {
 7365:                     $statushash->{$student}{'st'}{$section} = $status;
 7366:                 }
 7367:             }
 7368:         }
 7369:     }
 7370:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7371:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7372:         my $now = time;
 7373:         my %displaystatus = ( previous => 'Expired',
 7374:                               active   => 'Active',
 7375:                               future   => 'Future',
 7376:                             );
 7377:         my %nothide;
 7378:         if ($hidepriv) {
 7379:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7380:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7381:                 if ($user !~ /:/) {
 7382:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7383:                 } else {
 7384:                     $nothide{$user} = 1;
 7385:                 }
 7386:             }
 7387:         }
 7388:         foreach my $person (sort(keys(%coursepersonnel))) {
 7389:             my $match = 0;
 7390:             my $secmatch = 0;
 7391:             my $status;
 7392:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7393:             $user =~ s/:$//;
 7394:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7395:             if ($end == -1 || $start == -1) {
 7396:                 next;
 7397:             }
 7398:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7399:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7400:                 my ($uname,$udom) = split(/:/,$user);
 7401:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7402:                     if (grep(/^all$/,@{$sections})) {
 7403:                         $secmatch = 1;
 7404:                     } elsif ($usec eq '') {
 7405:                         if (grep(/^none$/,@{$sections})) {
 7406:                             $secmatch = 1;
 7407:                         }
 7408:                     } else {
 7409:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7410:                             $secmatch = 1;
 7411:                         }
 7412:                     }
 7413:                     if (!$secmatch) {
 7414:                         next;
 7415:                     }
 7416:                 }
 7417:                 if ($usec eq '') {
 7418:                     $usec = 'none';
 7419:                 }
 7420:                 if ($uname ne '' && $udom ne '') {
 7421:                     if ($hidepriv) {
 7422:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7423:                             (!$nothide{$uname.':'.$udom})) {
 7424:                             next;
 7425:                         }
 7426:                     }
 7427:                     if ($end > 0 && $end < $now) {
 7428:                         $status = 'previous';
 7429:                     } elsif ($start > $now) {
 7430:                         $status = 'future';
 7431:                     } else {
 7432:                         $status = 'active';
 7433:                     }
 7434:                     foreach my $type (keys(%{$types})) { 
 7435:                         if ($status eq $type) {
 7436:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7437:                                 push(@{$$users{$role}{$user}},$type);
 7438:                             }
 7439:                             $match = 1;
 7440:                         }
 7441:                     }
 7442:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7443:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7444: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7445:                         }
 7446:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7447:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7448:                         }
 7449:                         if (ref($statushash) eq 'HASH') {
 7450:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7451:                         }
 7452:                     }
 7453:                 }
 7454:             }
 7455:         }
 7456:         if (grep(/^ow$/,@{$roles})) {
 7457:             if ((defined($cdom)) && (defined($cnum))) {
 7458:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7459:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7460:                     my $owner = $csettings{'internal.courseowner'};
 7461:                     next if ($owner eq '');
 7462:                     my ($ownername,$ownerdom);
 7463:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7464:                         $ownername = $1;
 7465:                         $ownerdom = $2;
 7466:                     } else {
 7467:                         $ownername = $owner;
 7468:                         $ownerdom = $cdom;
 7469:                         $owner = $ownername.':'.$ownerdom;
 7470:                     }
 7471:                     @{$$users{'ow'}{$owner}} = 'any';
 7472:                     if (defined($userdata) && 
 7473: 			!exists($$userdata{$owner})) {
 7474: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7475:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7476:                             push(@{$seclists{$owner}},'none');
 7477:                         }
 7478:                         if (ref($statushash) eq 'HASH') {
 7479:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7480:                         }
 7481: 		    }
 7482:                 }
 7483:             }
 7484:         }
 7485:         foreach my $user (keys(%seclists)) {
 7486:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7487:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7488:         }
 7489:     }
 7490:     return;
 7491: }
 7492: 
 7493: sub get_user_info {
 7494:     my ($udom,$uname,$idx,$userdata) = @_;
 7495:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7496: 	&plainname($uname,$udom,'lastname');
 7497:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7498:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7499:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7500:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7501:     return;
 7502: }
 7503: 
 7504: ###############################################
 7505: 
 7506: =pod
 7507: 
 7508: =item * &get_user_quota()
 7509: 
 7510: Retrieves quota assigned for storage of portfolio files for a user  
 7511: 
 7512: Incoming parameters:
 7513: 1. user's username
 7514: 2. user's domain
 7515: 
 7516: Returns:
 7517: 1. Disk quota (in Mb) assigned to student.
 7518: 2. (Optional) Type of setting: custom or default
 7519:    (individually assigned or default for user's 
 7520:    institutional status).
 7521: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7522:    or student - types as defined in localenroll::inst_usertypes 
 7523:    for user's domain, which determines default quota for user.
 7524: 4. (Optional) - Default quota which would apply to the user.
 7525: 
 7526: If a value has been stored in the user's environment, 
 7527: it will return that, otherwise it returns the maximal default
 7528: defined for the user's instituional status(es) in the domain.
 7529: 
 7530: =cut
 7531: 
 7532: ###############################################
 7533: 
 7534: 
 7535: sub get_user_quota {
 7536:     my ($uname,$udom) = @_;
 7537:     my ($quota,$quotatype,$settingstatus,$defquota);
 7538:     if (!defined($udom)) {
 7539:         $udom = $env{'user.domain'};
 7540:     }
 7541:     if (!defined($uname)) {
 7542:         $uname = $env{'user.name'};
 7543:     }
 7544:     if (($udom eq '' || $uname eq '') ||
 7545:         ($udom eq 'public') && ($uname eq 'public')) {
 7546:         $quota = 0;
 7547:         $quotatype = 'default';
 7548:         $defquota = 0; 
 7549:     } else {
 7550:         my $inststatus;
 7551:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7552:             $quota = $env{'environment.portfolioquota'};
 7553:             $inststatus = $env{'environment.inststatus'};
 7554:         } else {
 7555:             my %userenv = 
 7556:                 &Apache::lonnet::get('environment',['portfolioquota',
 7557:                                      'inststatus'],$udom,$uname);
 7558:             my ($tmp) = keys(%userenv);
 7559:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7560:                 $quota = $userenv{'portfolioquota'};
 7561:                 $inststatus = $userenv{'inststatus'};
 7562:             } else {
 7563:                 undef(%userenv);
 7564:             }
 7565:         }
 7566:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7567:         if ($quota eq '') {
 7568:             $quota = $defquota;
 7569:             $quotatype = 'default';
 7570:         } else {
 7571:             $quotatype = 'custom';
 7572:         }
 7573:     }
 7574:     if (wantarray) {
 7575:         return ($quota,$quotatype,$settingstatus,$defquota);
 7576:     } else {
 7577:         return $quota;
 7578:     }
 7579: }
 7580: 
 7581: ###############################################
 7582: 
 7583: =pod
 7584: 
 7585: =item * &default_quota()
 7586: 
 7587: Retrieves default quota assigned for storage of user portfolio files,
 7588: given an (optional) user's institutional status.
 7589: 
 7590: Incoming parameters:
 7591: 1. domain
 7592: 2. (Optional) institutional status(es).  This is a : separated list of 
 7593:    status types (e.g., faculty, staff, student etc.)
 7594:    which apply to the user for whom the default is being retrieved.
 7595:    If the institutional status string in undefined, the domain
 7596:    default quota will be returned. 
 7597: 
 7598: Returns:
 7599: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7600: 2. (Optional) institutional type which determined the value of the
 7601:    default quota.
 7602: 
 7603: If a value has been stored in the domain's configuration db,
 7604: it will return that, otherwise it returns 20 (for backwards 
 7605: compatibility with domains which have not set up a configuration
 7606: db file; the original statically defined portfolio quota was 20 Mb). 
 7607: 
 7608: If the user's status includes multiple types (e.g., staff and student),
 7609: the largest default quota which applies to the user determines the
 7610: default quota returned.
 7611: 
 7612: =back
 7613: 
 7614: =cut
 7615: 
 7616: ###############################################
 7617: 
 7618: 
 7619: sub default_quota {
 7620:     my ($udom,$inststatus) = @_;
 7621:     my ($defquota,$settingstatus);
 7622:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7623:                                             ['quotas'],$udom);
 7624:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7625:         if ($inststatus ne '') {
 7626:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7627:             foreach my $item (@statuses) {
 7628:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7629:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7630:                         if ($defquota eq '') {
 7631:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7632:                             $settingstatus = $item;
 7633:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7634:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7635:                             $settingstatus = $item;
 7636:                         }
 7637:                     }
 7638:                 } else {
 7639:                     if ($quotahash{'quotas'}{$item} ne '') {
 7640:                         if ($defquota eq '') {
 7641:                             $defquota = $quotahash{'quotas'}{$item};
 7642:                             $settingstatus = $item;
 7643:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7644:                             $defquota = $quotahash{'quotas'}{$item};
 7645:                             $settingstatus = $item;
 7646:                         }
 7647:                     }
 7648:                 }
 7649:             }
 7650:         }
 7651:         if ($defquota eq '') {
 7652:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7653:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7654:             } else {
 7655:                 $defquota = $quotahash{'quotas'}{'default'};
 7656:             }
 7657:             $settingstatus = 'default';
 7658:         }
 7659:     } else {
 7660:         $settingstatus = 'default';
 7661:         $defquota = 20;
 7662:     }
 7663:     if (wantarray) {
 7664:         return ($defquota,$settingstatus);
 7665:     } else {
 7666:         return $defquota;
 7667:     }
 7668: }
 7669: 
 7670: sub get_secgrprole_info {
 7671:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7672:     my %sections_count = &get_sections($cdom,$cnum);
 7673:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7674:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7675:     my @groups = sort(keys(%curr_groups));
 7676:     my $allroles = [];
 7677:     my $rolehash;
 7678:     my $accesshash = {
 7679:                      active => 'Currently has access',
 7680:                      future => 'Will have future access',
 7681:                      previous => 'Previously had access',
 7682:                   };
 7683:     if ($needroles) {
 7684:         $rolehash = {'all' => 'all'};
 7685:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7686: 	if (&Apache::lonnet::error(%user_roles)) {
 7687: 	    undef(%user_roles);
 7688: 	}
 7689:         foreach my $item (keys(%user_roles)) {
 7690:             my ($role)=split(/\:/,$item,2);
 7691:             if ($role eq 'cr') { next; }
 7692:             if ($role =~ /^cr/) {
 7693:                 $$rolehash{$role} = (split('/',$role))[3];
 7694:             } else {
 7695:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7696:             }
 7697:         }
 7698:         foreach my $key (sort(keys(%{$rolehash}))) {
 7699:             push(@{$allroles},$key);
 7700:         }
 7701:         push (@{$allroles},'st');
 7702:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7703:     }
 7704:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7705: }
 7706: 
 7707: sub user_picker {
 7708:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 7709:     my $currdom = $dom;
 7710:     my %curr_selected = (
 7711:                         srchin => 'dom',
 7712:                         srchby => 'lastname',
 7713:                       );
 7714:     my $srchterm;
 7715:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7716:         if ($srch->{'srchby'} ne '') {
 7717:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7718:         }
 7719:         if ($srch->{'srchin'} ne '') {
 7720:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7721:         }
 7722:         if ($srch->{'srchtype'} ne '') {
 7723:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7724:         }
 7725:         if ($srch->{'srchdomain'} ne '') {
 7726:             $currdom = $srch->{'srchdomain'};
 7727:         }
 7728:         $srchterm = $srch->{'srchterm'};
 7729:     }
 7730:     my %lt=&Apache::lonlocal::texthash(
 7731:                     'usr'       => 'Search criteria',
 7732:                     'doma'      => 'Domain/institution to search',
 7733:                     'uname'     => 'username',
 7734:                     'lastname'  => 'last name',
 7735:                     'lastfirst' => 'last name, first name',
 7736:                     'crs'       => 'in this course',
 7737:                     'dom'       => 'in selected LON-CAPA domain', 
 7738:                     'alc'       => 'all LON-CAPA',
 7739:                     'instd'     => 'in institutional directory for selected domain',
 7740:                     'exact'     => 'is',
 7741:                     'contains'  => 'contains',
 7742:                     'begins'    => 'begins with',
 7743:                     'youm'      => "You must include some text to search for.",
 7744:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7745:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7746:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7747:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7748:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7749:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7750:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7751:                                        );
 7752:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7753:     my $srchinsel = ' <select name="srchin">';
 7754: 
 7755:     my @srchins = ('crs','dom','alc','instd');
 7756: 
 7757:     foreach my $option (@srchins) {
 7758:         # FIXME 'alc' option unavailable until 
 7759:         #       loncreateuser::print_user_query_page()
 7760:         #       has been completed.
 7761:         next if ($option eq 'alc');
 7762:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7763:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7764:         if ($curr_selected{'srchin'} eq $option) {
 7765:             $srchinsel .= ' 
 7766:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7767:         } else {
 7768:             $srchinsel .= '
 7769:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7770:         }
 7771:     }
 7772:     $srchinsel .= "\n  </select>\n";
 7773: 
 7774:     my $srchbysel =  ' <select name="srchby">';
 7775:     foreach my $option ('lastname','lastfirst','uname') {
 7776:         if ($curr_selected{'srchby'} eq $option) {
 7777:             $srchbysel .= '
 7778:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7779:         } else {
 7780:             $srchbysel .= '
 7781:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7782:          }
 7783:     }
 7784:     $srchbysel .= "\n  </select>\n";
 7785: 
 7786:     my $srchtypesel = ' <select name="srchtype">';
 7787:     foreach my $option ('begins','contains','exact') {
 7788:         if ($curr_selected{'srchtype'} eq $option) {
 7789:             $srchtypesel .= '
 7790:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7791:         } else {
 7792:             $srchtypesel .= '
 7793:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7794:         }
 7795:     }
 7796:     $srchtypesel .= "\n  </select>\n";
 7797: 
 7798:     my ($newuserscript,$new_user_create);
 7799:     my $context_dom = $env{'request.role.domain'};
 7800:     if ($context eq 'requestcrs') {
 7801:         if ($env{'form.coursedom'} ne '') { 
 7802:             $context_dom = $env{'form.coursedom'};
 7803:         }
 7804:     }
 7805:     if ($forcenewuser) {
 7806:         if (ref($srch) eq 'HASH') {
 7807:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 7808:                 if ($cancreate) {
 7809:                     $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>';
 7810:                 } else {
 7811:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7812:                     my %usertypetext = (
 7813:                         official   => 'institutional',
 7814:                         unofficial => 'non-institutional',
 7815:                     );
 7816:                     $new_user_create = '<p class="LC_warning">'
 7817:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7818:                                       .' '
 7819:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7820:                                           ,'<a href="'.$helplink.'">','</a>')
 7821:                                       .'</p><br />';
 7822:                 }
 7823:             }
 7824:         }
 7825: 
 7826:         $newuserscript = <<"ENDSCRIPT";
 7827: 
 7828: function setSearch(createnew,callingForm) {
 7829:     if (createnew == 1) {
 7830:         for (var i=0; i<callingForm.srchby.length; i++) {
 7831:             if (callingForm.srchby.options[i].value == 'uname') {
 7832:                 callingForm.srchby.selectedIndex = i;
 7833:             }
 7834:         }
 7835:         for (var i=0; i<callingForm.srchin.length; i++) {
 7836:             if ( callingForm.srchin.options[i].value == 'dom') {
 7837: 		callingForm.srchin.selectedIndex = i;
 7838:             }
 7839:         }
 7840:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7841:             if (callingForm.srchtype.options[i].value == 'exact') {
 7842:                 callingForm.srchtype.selectedIndex = i;
 7843:             }
 7844:         }
 7845:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7846:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 7847:                 callingForm.srchdomain.selectedIndex = i;
 7848:             }
 7849:         }
 7850:     }
 7851: }
 7852: ENDSCRIPT
 7853: 
 7854:     }
 7855: 
 7856:     my $output = <<"END_BLOCK";
 7857: <script type="text/javascript">
 7858: // <![CDATA[
 7859: function validateEntry(callingForm) {
 7860: 
 7861:     var checkok = 1;
 7862:     var srchin;
 7863:     for (var i=0; i<callingForm.srchin.length; i++) {
 7864: 	if ( callingForm.srchin[i].checked ) {
 7865: 	    srchin = callingForm.srchin[i].value;
 7866: 	}
 7867:     }
 7868: 
 7869:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7870:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7871:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7872:     var srchterm =  callingForm.srchterm.value;
 7873:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7874:     var msg = "";
 7875: 
 7876:     if (srchterm == "") {
 7877:         checkok = 0;
 7878:         msg += "$lt{'youm'}\\n";
 7879:     }
 7880: 
 7881:     if (srchtype== 'begins') {
 7882:         if (srchterm.length < 2) {
 7883:             checkok = 0;
 7884:             msg += "$lt{'thte'}\\n";
 7885:         }
 7886:     }
 7887: 
 7888:     if (srchtype== 'contains') {
 7889:         if (srchterm.length < 3) {
 7890:             checkok = 0;
 7891:             msg += "$lt{'thet'}\\n";
 7892:         }
 7893:     }
 7894:     if (srchin == 'instd') {
 7895:         if (srchdomain == '') {
 7896:             checkok = 0;
 7897:             msg += "$lt{'yomc'}\\n";
 7898:         }
 7899:     }
 7900:     if (srchin == 'dom') {
 7901:         if (srchdomain == '') {
 7902:             checkok = 0;
 7903:             msg += "$lt{'ymcd'}\\n";
 7904:         }
 7905:     }
 7906:     if (srchby == 'lastfirst') {
 7907:         if (srchterm.indexOf(",") == -1) {
 7908:             checkok = 0;
 7909:             msg += "$lt{'whus'}\\n";
 7910:         }
 7911:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7912:             checkok = 0;
 7913:             msg += "$lt{'whse'}\\n";
 7914:         }
 7915:     }
 7916:     if (checkok == 0) {
 7917:         alert("$lt{'thfo'}\\n"+msg);
 7918:         return;
 7919:     }
 7920:     if (checkok == 1) {
 7921:         callingForm.submit();
 7922:     }
 7923: }
 7924: 
 7925: $newuserscript
 7926: 
 7927: // ]]>
 7928: </script>
 7929: 
 7930: $new_user_create
 7931: 
 7932: END_BLOCK
 7933: 
 7934:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7935:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7936:                $domform.
 7937:                &Apache::lonhtmlcommon::row_closure().
 7938:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7939:                $srchbysel.
 7940:                $srchtypesel. 
 7941:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7942:                $srchinsel.
 7943:                &Apache::lonhtmlcommon::row_closure(1). 
 7944:                &Apache::lonhtmlcommon::end_pick_box().
 7945:                '<br />';
 7946:     return $output;
 7947: }
 7948: 
 7949: sub user_rule_check {
 7950:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7951:     my $response;
 7952:     if (ref($usershash) eq 'HASH') {
 7953:         foreach my $user (keys(%{$usershash})) {
 7954:             my ($uname,$udom) = split(/:/,$user);
 7955:             next if ($udom eq '' || $uname eq '');
 7956:             my ($id,$newuser);
 7957:             if (ref($usershash->{$user}) eq 'HASH') {
 7958:                 $newuser = $usershash->{$user}->{'newuser'};
 7959:                 $id = $usershash->{$user}->{'id'};
 7960:             }
 7961:             my $inst_response;
 7962:             if (ref($checks) eq 'HASH') {
 7963:                 if (defined($checks->{'username'})) {
 7964:                     ($inst_response,%{$inst_results->{$user}}) = 
 7965:                         &Apache::lonnet::get_instuser($udom,$uname);
 7966:                 } elsif (defined($checks->{'id'})) {
 7967:                     ($inst_response,%{$inst_results->{$user}}) =
 7968:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7969:                 }
 7970:             } else {
 7971:                 ($inst_response,%{$inst_results->{$user}}) =
 7972:                     &Apache::lonnet::get_instuser($udom,$uname);
 7973:                 return;
 7974:             }
 7975:             if (!$got_rules->{$udom}) {
 7976:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7977:                                                   ['usercreation'],$udom);
 7978:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7979:                     foreach my $item ('username','id') {
 7980:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7981:                             $$curr_rules{$udom}{$item} = 
 7982:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7983:                         }
 7984:                     }
 7985:                 }
 7986:                 $got_rules->{$udom} = 1;  
 7987:             }
 7988:             foreach my $item (keys(%{$checks})) {
 7989:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7990:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7991:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7992:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7993:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7994:                                 if ($rule_check{$rule}) {
 7995:                                     $$rulematch{$user}{$item} = $rule;
 7996:                                     if ($inst_response eq 'ok') {
 7997:                                         if (ref($inst_results) eq 'HASH') {
 7998:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7999:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8000:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8001:                                                 }
 8002:                                             }
 8003:                                         }
 8004:                                     }
 8005:                                     last;
 8006:                                 }
 8007:                             }
 8008:                         }
 8009:                     }
 8010:                 }
 8011:             }
 8012:         }
 8013:     }
 8014:     return;
 8015: }
 8016: 
 8017: sub user_rule_formats {
 8018:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8019:     my %text = ( 
 8020:                  'username' => 'Usernames',
 8021:                  'id'       => 'IDs',
 8022:                );
 8023:     my $output;
 8024:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8025:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8026:         if (@{$ruleorder} > 0) {
 8027:             $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>';
 8028:             foreach my $rule (@{$ruleorder}) {
 8029:                 if (ref($curr_rules) eq 'ARRAY') {
 8030:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8031:                         if (ref($rules->{$rule}) eq 'HASH') {
 8032:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8033:                                         $rules->{$rule}{'desc'}.'</li>';
 8034:                         }
 8035:                     }
 8036:                 }
 8037:             }
 8038:             $output .= '</ul>';
 8039:         }
 8040:     }
 8041:     return $output;
 8042: }
 8043: 
 8044: sub instrule_disallow_msg {
 8045:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8046:     my $response;
 8047:     my %text = (
 8048:                   item   => 'username',
 8049:                   items  => 'usernames',
 8050:                   match  => 'matches',
 8051:                   do     => 'does',
 8052:                   action => 'a username',
 8053:                   one    => 'one',
 8054:                );
 8055:     if ($count > 1) {
 8056:         $text{'item'} = 'usernames';
 8057:         $text{'match'} ='match';
 8058:         $text{'do'} = 'do';
 8059:         $text{'action'} = 'usernames',
 8060:         $text{'one'} = 'ones';
 8061:     }
 8062:     if ($checkitem eq 'id') {
 8063:         $text{'items'} = 'IDs';
 8064:         $text{'item'} = 'ID';
 8065:         $text{'action'} = 'an ID';
 8066:         if ($count > 1) {
 8067:             $text{'item'} = 'IDs';
 8068:             $text{'action'} = 'IDs';
 8069:         }
 8070:     }
 8071:     $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 />';
 8072:     if ($mode eq 'upload') {
 8073:         if ($checkitem eq 'username') {
 8074:             $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'}.");
 8075:         } elsif ($checkitem eq 'id') {
 8076:             $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.");
 8077:         }
 8078:     } elsif ($mode eq 'selfcreate') {
 8079:         if ($checkitem eq 'id') {
 8080:             $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.");
 8081:         }
 8082:     } else {
 8083:         if ($checkitem eq 'username') {
 8084:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8085:         } elsif ($checkitem eq 'id') {
 8086:             $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.");
 8087:         }
 8088:     }
 8089:     return $response;
 8090: }
 8091: 
 8092: sub personal_data_fieldtitles {
 8093:     my %fieldtitles = &Apache::lonlocal::texthash (
 8094:                         id => 'Student/Employee ID',
 8095:                         permanentemail => 'E-mail address',
 8096:                         lastname => 'Last Name',
 8097:                         firstname => 'First Name',
 8098:                         middlename => 'Middle Name',
 8099:                         generation => 'Generation',
 8100:                         gen => 'Generation',
 8101:                         inststatus => 'Affiliation',
 8102:                    );
 8103:     return %fieldtitles;
 8104: }
 8105: 
 8106: sub sorted_inst_types {
 8107:     my ($dom) = @_;
 8108:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8109:     my $othertitle = &mt('All users');
 8110:     if ($env{'request.course.id'}) {
 8111:         $othertitle  = &mt('Any users');
 8112:     }
 8113:     my @types;
 8114:     if (ref($order) eq 'ARRAY') {
 8115:         @types = @{$order};
 8116:     }
 8117:     if (@types == 0) {
 8118:         if (ref($usertypes) eq 'HASH') {
 8119:             @types = sort(keys(%{$usertypes}));
 8120:         }
 8121:     }
 8122:     if (keys(%{$usertypes}) > 0) {
 8123:         $othertitle = &mt('Other users');
 8124:     }
 8125:     return ($othertitle,$usertypes,\@types);
 8126: }
 8127: 
 8128: sub get_institutional_codes {
 8129:     my ($settings,$allcourses,$LC_code) = @_;
 8130: # Get complete list of course sections to update
 8131:     my @currsections = ();
 8132:     my @currxlists = ();
 8133:     my $coursecode = $$settings{'internal.coursecode'};
 8134: 
 8135:     if ($$settings{'internal.sectionnums'} ne '') {
 8136:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8137:     }
 8138: 
 8139:     if ($$settings{'internal.crosslistings'} ne '') {
 8140:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8141:     }
 8142: 
 8143:     if (@currxlists > 0) {
 8144:         foreach (@currxlists) {
 8145:             if (m/^([^:]+):(\w*)$/) {
 8146:                 unless (grep/^$1$/,@{$allcourses}) {
 8147:                     push @{$allcourses},$1;
 8148:                     $$LC_code{$1} = $2;
 8149:                 }
 8150:             }
 8151:         }
 8152:     }
 8153:  
 8154:     if (@currsections > 0) {
 8155:         foreach (@currsections) {
 8156:             if (m/^(\w+):(\w*)$/) {
 8157:                 my $sec = $coursecode.$1;
 8158:                 my $lc_sec = $2;
 8159:                 unless (grep/^$sec$/,@{$allcourses}) {
 8160:                     push @{$allcourses},$sec;
 8161:                     $$LC_code{$sec} = $lc_sec;
 8162:                 }
 8163:             }
 8164:         }
 8165:     }
 8166:     return;
 8167: }
 8168: 
 8169: sub get_standard_codeitems {
 8170:     return ('Year','Semester','Department','Number','Section');
 8171: }
 8172: 
 8173: =pod
 8174: 
 8175: =head1 Slot Helpers
 8176: 
 8177: =over 4
 8178: 
 8179: =item * sorted_slots()
 8180: 
 8181: Sorts an array of slot names in order of slot start time (earliest first). 
 8182: 
 8183: Inputs:
 8184: 
 8185: =over 4
 8186: 
 8187: slotsarr  - Reference to array of unsorted slot names.
 8188: 
 8189: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8190: 
 8191: =back
 8192: 
 8193: Returns:
 8194: 
 8195: =over 4
 8196: 
 8197: sorted   - An array of slot names sorted by the start time of the slot.
 8198: 
 8199: =back
 8200: 
 8201: =back
 8202: 
 8203: =cut
 8204: 
 8205: 
 8206: sub sorted_slots {
 8207:     my ($slotsarr,$slots) = @_;
 8208:     my @sorted;
 8209:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8210:         @sorted =
 8211:             sort {
 8212:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8213:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8214:                      }
 8215:                      if (ref($slots->{$a})) { return -1;}
 8216:                      if (ref($slots->{$b})) { return 1;}
 8217:                      return 0;
 8218:                  } @{$slotsarr};
 8219:     }
 8220:     return @sorted;
 8221: }
 8222: 
 8223: 
 8224: =pod
 8225: 
 8226: =head1 HTTP Helpers
 8227: 
 8228: =over 4
 8229: 
 8230: =item * &get_unprocessed_cgi($query,$possible_names)
 8231: 
 8232: Modify the %env hash to contain unprocessed CGI form parameters held in
 8233: $query.  The parameters listed in $possible_names (an array reference),
 8234: will be set in $env{'form.name'} if they do not already exist.
 8235: 
 8236: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8237: $possible_names is an ref to an array of form element names.  As an example:
 8238: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8239: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8240: 
 8241: =cut
 8242: 
 8243: sub get_unprocessed_cgi {
 8244:   my ($query,$possible_names)= @_;
 8245:   # $Apache::lonxml::debug=1;
 8246:   foreach my $pair (split(/&/,$query)) {
 8247:     my ($name, $value) = split(/=/,$pair);
 8248:     $name = &unescape($name);
 8249:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8250:       $value =~ tr/+/ /;
 8251:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8252:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8253:     }
 8254:   }
 8255: }
 8256: 
 8257: =pod
 8258: 
 8259: =item * &cacheheader() 
 8260: 
 8261: returns cache-controlling header code
 8262: 
 8263: =cut
 8264: 
 8265: sub cacheheader {
 8266:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8267:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8268:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8269:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8270:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8271:     return $output;
 8272: }
 8273: 
 8274: =pod
 8275: 
 8276: =item * &no_cache($r) 
 8277: 
 8278: specifies header code to not have cache
 8279: 
 8280: =cut
 8281: 
 8282: sub no_cache {
 8283:     my ($r) = @_;
 8284:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8285: 	$env{'request.method'} ne 'GET') { return ''; }
 8286:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8287:     $r->no_cache(1);
 8288:     $r->header_out("Expires" => $date);
 8289:     $r->header_out("Pragma" => "no-cache");
 8290: }
 8291: 
 8292: sub content_type {
 8293:     my ($r,$type,$charset) = @_;
 8294:     if ($r) {
 8295: 	#  Note that printout.pl calls this with undef for $r.
 8296: 	&no_cache($r);
 8297:     }
 8298:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8299:     unless ($charset) {
 8300: 	$charset=&Apache::lonlocal::current_encoding;
 8301:     }
 8302:     if ($charset) { $type.='; charset='.$charset; }
 8303:     if ($r) {
 8304: 	$r->content_type($type);
 8305:     } else {
 8306: 	print("Content-type: $type\n\n");
 8307:     }
 8308: }
 8309: 
 8310: =pod
 8311: 
 8312: =item * &add_to_env($name,$value) 
 8313: 
 8314: adds $name to the %env hash with value
 8315: $value, if $name already exists, the entry is converted to an array
 8316: reference and $value is added to the array.
 8317: 
 8318: =cut
 8319: 
 8320: sub add_to_env {
 8321:   my ($name,$value)=@_;
 8322:   if (defined($env{$name})) {
 8323:     if (ref($env{$name})) {
 8324:       #already have multiple values
 8325:       push(@{ $env{$name} },$value);
 8326:     } else {
 8327:       #first time seeing multiple values, convert hash entry to an arrayref
 8328:       my $first=$env{$name};
 8329:       undef($env{$name});
 8330:       push(@{ $env{$name} },$first,$value);
 8331:     }
 8332:   } else {
 8333:     $env{$name}=$value;
 8334:   }
 8335: }
 8336: 
 8337: =pod
 8338: 
 8339: =item * &get_env_multiple($name) 
 8340: 
 8341: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8342: values may be defined and end up as an array ref.
 8343: 
 8344: returns an array of values
 8345: 
 8346: =cut
 8347: 
 8348: sub get_env_multiple {
 8349:     my ($name) = @_;
 8350:     my @values;
 8351:     if (defined($env{$name})) {
 8352:         # exists is it an array
 8353:         if (ref($env{$name})) {
 8354:             @values=@{ $env{$name} };
 8355:         } else {
 8356:             $values[0]=$env{$name};
 8357:         }
 8358:     }
 8359:     return(@values);
 8360: }
 8361: 
 8362: sub ask_for_embedded_content {
 8363:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8364:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
 8365:     my $num = 0;
 8366:     my $numremref = 0;
 8367:     my $numinvalid = 0;
 8368:     my $numpathchg = 0;
 8369:     my $numexisting = 0;
 8370:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
 8371:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8372:         my $current_path='/';
 8373:         if ($env{'form.currentpath'}) {
 8374:             $current_path = $env{'form.currentpath'};
 8375:         }
 8376:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 8377:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8378:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 8379:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 8380:         } else {
 8381:             $udom = $env{'user.domain'};
 8382:             $uname = $env{'user.name'};
 8383:             $url = '/userfiles/portfolio';
 8384:         }
 8385:         $toplevel = $url.'/';
 8386:         $url .= $current_path;
 8387:         $getpropath = 1;
 8388:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8389:              ($actionurl eq '/adm/imsimport')) { 
 8390:         ($uname,my $rest) = ($args->{'current_path'} =~ m{/priv/($match_username)/?(.*)$});
 8391:         $url = '/home/'.$uname.'/public_html/';
 8392:         $toplevel = $url;
 8393:         if ($rest ne '') {
 8394:             $url .= $rest;
 8395:         }
 8396:     } elsif ($actionurl eq '/adm/coursedocs') {
 8397:         if (ref($args) eq 'HASH') {
 8398:            $url = $args->{'docs_url'};
 8399:            $toplevel = $url;
 8400:         }
 8401:     }
 8402:     my $now = time();
 8403:     foreach my $embed_file (keys(%{$allfiles})) {
 8404:         my $absolutepath;
 8405:         if ($embed_file =~ m{^\w+://}) {
 8406:             $newfiles{$embed_file} = 1;
 8407:             $mapping{$embed_file} = $embed_file;
 8408:         } else {
 8409:             if ($embed_file =~ m{^/}) {
 8410:                 $absolutepath = $embed_file;
 8411:                 $embed_file =~ s{^(/+)}{};
 8412:             }
 8413:             if ($embed_file =~ m{/}) {
 8414:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 8415:                 $path = &check_for_traversal($path,$url,$toplevel);
 8416:                 my $item = $fname;
 8417:                 if ($path ne '') {
 8418:                     $item = $path.'/'.$fname;
 8419:                     $subdependencies{$path}{$fname} = 1;
 8420:                 } else {
 8421:                     $dependencies{$item} = 1;
 8422:                 }
 8423:                 if ($absolutepath) {
 8424:                     $mapping{$item} = $absolutepath;
 8425:                 } else {
 8426:                     $mapping{$item} = $embed_file;
 8427:                 }
 8428:             } else {
 8429:                 $dependencies{$embed_file} = 1;
 8430:                 if ($absolutepath) {
 8431:                     $mapping{$embed_file} = $absolutepath;
 8432:                 } else {
 8433:                     $mapping{$embed_file} = $embed_file;
 8434:                 }
 8435:             }
 8436:         }
 8437:     }
 8438:     foreach my $path (keys(%subdependencies)) {
 8439:         my %currsubfile;
 8440:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 8441:             my @subdir_list = &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 8442:             foreach my $line (@subdir_list) {
 8443:                 my ($file_name,$rest) = split(/\&/,$line,2);
 8444:                 $currsubfile{$file_name} = 1;
 8445:             }
 8446:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8447:             if (opendir(my $dir,$url.'/'.$path)) {
 8448:                 my @subdir_list = grep(!/^\./,readdir($dir));
 8449:                 map {$currsubfile{$_} = 1;} @subdir_list;
 8450:             }
 8451:         }
 8452:         foreach my $file (keys(%{$subdependencies{$path}})) {
 8453:             if ($currsubfile{$file}) {
 8454:                 my $item = $path.'/'.$file;
 8455:                 unless ($mapping{$item} eq $item) {
 8456:                     $pathchanges{$item} = 1;
 8457:                 }
 8458:                 $existing{$item} = 1;
 8459:                 $numexisting ++;
 8460:             } else {
 8461:                 $newfiles{$path.'/'.$file} = 1;
 8462:             }
 8463:         }
 8464:     }
 8465:     my %currfile;
 8466:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8467:         my @dir_list = &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 8468:         foreach my $line (@dir_list) {
 8469:             my ($file_name,$rest) = split(/\&/,$line,2);
 8470:             $currfile{$file_name} = 1;
 8471:         }
 8472:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8473:         if (opendir(my $dir,$url)) {
 8474:             my @dir_list = grep(!/^\./,readdir($dir));
 8475:             map {$currfile{$_} = 1;} @dir_list;
 8476:         }
 8477:     }
 8478:     foreach my $file (keys(%dependencies)) {
 8479:         if ($currfile{$file}) {
 8480:             unless ($mapping{$file} eq $file) {
 8481:                 $pathchanges{$file} = 1;
 8482:             }
 8483:             $existing{$file} = 1;
 8484:             $numexisting ++;
 8485:         } else {
 8486:             $newfiles{$file} = 1;
 8487:         }
 8488:     }
 8489:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 8490:         $upload_output .= &start_data_table_row().
 8491:                           '<td><span class="LC_filename">'.$embed_file.'</span>';
 8492:         unless ($mapping{$embed_file} eq $embed_file) {
 8493:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 8494:         }
 8495:         $upload_output .= '</td><td>';
 8496:         if ($args->{'ignore_remote_references'}
 8497:             && $embed_file =~ m{^\w+://}) {
 8498:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8499:             $numremref++;
 8500:         } elsif ($args->{'error_on_invalid_names'}
 8501:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8502: 
 8503:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 8504:             $numinvalid++;
 8505:         } else {
 8506:             $upload_output .= &embedded_file_element('upload_embedded',$num,
 8507:                                                      $embed_file,\%mapping,
 8508:                                                      $allfiles,$codebase);
 8509:             $num++;
 8510:         }
 8511:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 8512:     }
 8513:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 8514:         $upload_output .= &start_data_table_row().
 8515:                           '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
 8516:                           '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 8517:                           &Apache::loncommon::end_data_table_row()."\n";
 8518:     }
 8519:     if ($upload_output) {
 8520:         $upload_output = &start_data_table().
 8521:                          $upload_output.
 8522:                          &end_data_table()."\n";
 8523:     }
 8524:     my $applies = 0;
 8525:     if ($numremref) {
 8526:         $applies ++;
 8527:     }
 8528:     if ($numinvalid) {
 8529:         $applies ++;
 8530:     }
 8531:     if ($numexisting) {
 8532:         $applies ++;
 8533:     }
 8534:     if ($num) {
 8535:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 8536:                   ' method="post" enctype="multipart/form-data">'."\n".
 8537:                   $state.
 8538:                   '<h3>'.&mt('Upload embedded files').
 8539:                   ':</h3>'.$upload_output.'<br />'."\n".
 8540:                   '<input type ="hidden" name="number_embedded_items" value="'.
 8541:                   $num.'" />'."\n";
 8542:         if ($actionurl eq '') {
 8543:             $output .=  '<input type="hidden" name="phase" value="three" />';
 8544:         }
 8545:     } elsif ($applies) {
 8546:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 8547:         if ($applies > 1) {
 8548:             $output .=  
 8549:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 8550:             if ($numremref) {
 8551:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 8552:             }
 8553:             if ($numinvalid) {
 8554:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 8555:             }
 8556:             if ($numexisting) {
 8557:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 8558:             }
 8559:             $output .= '</ul><br />';
 8560:         } elsif ($numremref) {
 8561:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 8562:         } elsif ($numinvalid) {
 8563:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 8564:         } elsif ($numexisting) {
 8565:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 8566:         }
 8567:         $output .= $upload_output.'<br />';
 8568:     }
 8569:     my ($pathchange_output,$chgcount);
 8570:     $chgcount = $num;
 8571:     if (keys(%pathchanges) > 0) {
 8572:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 8573:             if ($num) {
 8574:                 $output .= &embedded_file_element('pathchange',$chgcount,
 8575:                                                   $embed_file,\%mapping,
 8576:                                                   $allfiles,$codebase);
 8577:             } else {
 8578:                 $pathchange_output .= 
 8579:                     &start_data_table_row().
 8580:                     '<td><input type ="checkbox" name="namechange" value="'.
 8581:                     $chgcount.'" checked="checked" /></td>'.
 8582:                     '<td>'.$mapping{$embed_file}.'</td>'.
 8583:                     '<td>'.$embed_file.
 8584:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 8585:                                            \%mapping,$allfiles,$codebase).
 8586:                     '</td>'.&end_data_table_row();
 8587:             }
 8588:             $numpathchg ++;
 8589:             $chgcount ++;
 8590:         }
 8591:     }
 8592:     if ($num) {
 8593:         if ($numpathchg) {
 8594:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 8595:                        $numpathchg.'" />'."\n";
 8596:         }
 8597:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 8598:             ($actionurl eq '/adm/imsimport')) {
 8599:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 8600:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 8601:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 8602:         }
 8603:         $output .=  '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
 8604:                     &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
 8605:     } elsif ($numpathchg) {
 8606:         my %pathchange = ();
 8607:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 8608:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8609:             $output .= '<p>'.&mt('or').'</p>'; 
 8610:         } 
 8611:     }
 8612:     return ($output,$num,$numpathchg);
 8613: }
 8614: 
 8615: sub embedded_file_element {
 8616:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
 8617:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 8618:                    (ref($codebase) eq 'HASH'));
 8619:     my $output;
 8620:     if ($context eq 'upload_embedded') {
 8621:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 8622:     }
 8623:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 8624:                &escape($embed_file).'" />';
 8625:     unless (($context eq 'upload_embedded') && 
 8626:             ($mapping->{$embed_file} eq $embed_file)) {
 8627:         $output .='
 8628:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 8629:     }
 8630:     my $attrib;
 8631:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 8632:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 8633:     }
 8634:     $output .=
 8635:         "\n\t\t".
 8636:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8637:         $attrib.'" />';
 8638:     if (exists($codebase->{$mapping->{$embed_file}})) {
 8639:         $output .=
 8640:             "\n\t\t".
 8641:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 8642:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 8643:     }
 8644:     return $output;
 8645: }
 8646: 
 8647: sub upload_embedded {
 8648:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8649:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 8650:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 8651:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8652:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8653:         my $orig_uploaded_filename =
 8654:             $env{'form.embedded_item_'.$i.'.filename'};
 8655:         foreach my $type ('orig','ref','attrib','codebase') {
 8656:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 8657:                 $env{'form.embedded_'.$type.'_'.$i} =
 8658:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 8659:             }
 8660:         }
 8661:         my ($path,$fname) =
 8662:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8663:         # no path, whole string is fname
 8664:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8665:         $fname = &Apache::lonnet::clean_filename($fname);
 8666:         # See if there is anything left
 8667:         next if ($fname eq '');
 8668: 
 8669:         # Check if file already exists as a file or directory.
 8670:         my ($state,$msg);
 8671:         if ($context eq 'portfolio') {
 8672:             my $port_path = $dirpath;
 8673:             if ($group ne '') {
 8674:                 $port_path = "groups/$group/$port_path";
 8675:             }
 8676:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 8677:                                               $fname,$group,'embedded_item_'.$i,
 8678:                                               $dir_root,$port_path,$disk_quota,
 8679:                                               $current_disk_usage,$uname,$udom);
 8680:             if ($state eq 'will_exceed_quota'
 8681:                 || $state eq 'file_locked') {
 8682:                 $output .= $msg;
 8683:                 next;
 8684:             }
 8685:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8686:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8687:             if ($state eq 'exists') {
 8688:                 $output .= $msg;
 8689:                 next;
 8690:             }
 8691:         }
 8692:         # Check if extension is valid
 8693:         if (($fname =~ /\.(\w+)$/) &&
 8694:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8695:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 8696:             next;
 8697:         } elsif (($fname =~ /\.(\w+)$/) &&
 8698:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8699:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 8700:             next;
 8701:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8702:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 8703:             next;
 8704:         }
 8705: 
 8706:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8707:         if ($context eq 'portfolio') {
 8708:             my $result;
 8709:             if ($state eq 'existingfile') {
 8710:                 $result=
 8711:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
 8712:                                                     $dirpath.$env{'form.currentpath'}.$path);
 8713:             } else {
 8714:                 $result=
 8715:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8716:                                                     $dirpath.
 8717:                                                     $env{'form.currentpath'}.$path);
 8718:                 if ($result !~ m|^/uploaded/|) {
 8719:                     $output .= '<span class="LC_error">'
 8720:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8721:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8722:                                .'</span><br />';
 8723:                     next;
 8724:                 } else {
 8725:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8726:                                $path.$fname.'</span>').'<br />';     
 8727:                 }
 8728:             }
 8729:         } elsif ($context eq 'coursedoc') {
 8730:             my $result =
 8731:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
 8732:                                                 $dirpath.'/'.$path);
 8733:             if ($result !~ m|^/uploaded/|) {
 8734:                 $output .= '<span class="LC_error">'
 8735:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8736:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8737:                            .'</span><br />';
 8738:                     next;
 8739:             } else {
 8740:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8741:                            $path.$fname.'</span>').'<br />';
 8742:             }
 8743:         } else {
 8744: # Save the file
 8745:             my $target = $env{'form.embedded_item_'.$i};
 8746:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8747:             my $dest = $fullpath.$fname;
 8748:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8749:             my @parts=split(/\//,$fullpath);
 8750:             my $count;
 8751:             my $filepath = $dir_root;
 8752:             for ($count=4;$count<=$#parts;$count++) {
 8753:                 $filepath .= "/$parts[$count]";
 8754:                 if ((-e $filepath)!=1) {
 8755:                     mkdir($filepath,0770);
 8756:                 }
 8757:             }
 8758:             my $fh;
 8759:             if (!open($fh,'>'.$dest)) {
 8760:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8761:                 $output .= '<span class="LC_error">'.
 8762:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8763:                            '</span><br />';
 8764:             } else {
 8765:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8766:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8767:                     $output .= '<span class="LC_error">'.
 8768:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8769:                               '</span><br />';
 8770:                 } else {
 8771:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8772:                                $url.'</span>').'<br />';
 8773:                     unless ($context eq 'testbank') {
 8774:                         $footer .= &mt('View embedded file: [_1]',
 8775:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
 8776:                     }
 8777:                 }
 8778:                 close($fh);
 8779:             }
 8780:         }
 8781:         if ($env{'form.embedded_ref_'.$i}) {
 8782:             $pathchange{$i} = 1;
 8783:         }
 8784:     }
 8785:     if ($output) {
 8786:         $output = '<p>'.$output.'</p>';
 8787:     }
 8788:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
 8789:     $returnflag = 'ok';
 8790:     if (keys(%pathchange) > 0) {
 8791:         if ($context eq 'portfolio') {
 8792:             $output .= '<p>'.&mt('or').'</p>';
 8793:         } elsif ($context eq 'testbank') {
 8794:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
 8795:             $returnflag = 'modify_orightml';
 8796:         }
 8797:     }
 8798:     return ($output.$footer,$returnflag);
 8799: }
 8800: 
 8801: sub modify_html_form {
 8802:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
 8803:     my $end = 0;
 8804:     my $modifyform;
 8805:     if ($context eq 'upload_embedded') {
 8806:         return unless (ref($pathchange) eq 'HASH');
 8807:         if ($env{'form.number_embedded_items'}) {
 8808:             $end += $env{'form.number_embedded_items'};
 8809:         }
 8810:         if ($env{'form.number_pathchange_items'}) {
 8811:             $end += $env{'form.number_pathchange_items'};
 8812:         }
 8813:         if ($end) {
 8814:             for (my $i=0; $i<$end; $i++) {
 8815:                 if ($i < $env{'form.number_embedded_items'}) {
 8816:                     next unless($pathchange->{$i});
 8817:                 }
 8818:                 $modifyform .=
 8819:                     &start_data_table_row().
 8820:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
 8821:                     'checked="checked" /></td>'.
 8822:                     '<td>'.$env{'form.embedded_ref_'.$i}.
 8823:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
 8824:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
 8825:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
 8826:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
 8827:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
 8828:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
 8829:                     '<td>'.$env{'form.embedded_orig_'.$i}.
 8830:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
 8831:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
 8832:                     &end_data_table_row();
 8833:             } 
 8834:         }
 8835:     } else {
 8836:         $modifyform = $pathchgtable;
 8837:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8838:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
 8839:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8840:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
 8841:         }
 8842:     }
 8843:     if ($modifyform) {
 8844:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
 8845:                '<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".
 8846:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
 8847:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
 8848:                '</ol></p>'."\n".'<p>'.
 8849:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
 8850:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
 8851:                &start_data_table()."\n".
 8852:                &start_data_table_header_row().
 8853:                '<th>'.&mt('Change?').'</th>'.
 8854:                '<th>'.&mt('Current reference').'</th>'.
 8855:                '<th>'.&mt('Required reference').'</th>'.
 8856:                &end_data_table_header_row()."\n".
 8857:                $modifyform.
 8858:                &end_data_table().'<br />'."\n".$hiddenstate.
 8859:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
 8860:                '</form>'."\n";
 8861:     }
 8862:     return;
 8863: }
 8864: 
 8865: sub modify_html_refs {
 8866:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
 8867:     my $container;
 8868:     if ($context eq 'portfolio') {
 8869:         $container = $env{'form.container'};
 8870:     } elsif ($context eq 'coursedoc') {
 8871:         $container = $env{'form.primaryurl'};
 8872:     } else {
 8873:         $container = $env{'form.filename'};
 8874:         $container =~ s{^/priv/(\Q$uname\E)/(.*)}{/home/$1/public_html/$2};
 8875:     }
 8876:     my (%allfiles,%codebase,$output,$content);
 8877:     my @changes = &get_env_multiple('form.namechange');
 8878:     return unless (@changes > 0);
 8879:     if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
 8880:         return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
 8881:         $content = &Apache::lonnet::getfile($container);
 8882:         return if ($content eq '-1');
 8883:     } else {
 8884:         return unless ($container =~ /^\Q$dir_root\E/); 
 8885:         if (open(my $fh,"<$container")) {
 8886:             $content = join('', <$fh>);
 8887:             close($fh);
 8888:         } else {
 8889:             return;
 8890:         }
 8891:     }
 8892:     my ($count,$codebasecount) = (0,0);
 8893:     my $mm = new File::MMagic;
 8894:     my $mime_type = $mm->checktype_contents($content);
 8895:     if ($mime_type eq 'text/html') {
 8896:         my $parse_result = 
 8897:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
 8898:                                                     \%codebase,\$content);
 8899:         if ($parse_result eq 'ok') {
 8900:             foreach my $i (@changes) {
 8901:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
 8902:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
 8903:                 if ($allfiles{$ref}) {
 8904:                     my $newname =  $orig;
 8905:                     my ($attrib_regexp,$codebase);
 8906:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
 8907:                     if ($attrib_regexp =~ /:/) {
 8908:                         $attrib_regexp =~ s/\:/|/g;
 8909:                     }
 8910:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
 8911:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
 8912:                         $count += $numchg;
 8913:                     }
 8914:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
 8915:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
 8916:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
 8917:                         $codebasecount ++;
 8918:                     }
 8919:                 }
 8920:             }
 8921:             if ($count || $codebasecount) {
 8922:                 my $saveresult;
 8923:                 if ($context eq 'portfolio' || $context eq 'coursedoc') {
 8924:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
 8925:                     if ($url eq $container) {
 8926:                         my ($fname) = ($container =~ m{/([^/]+)$});
 8927:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 8928:                                             $count,'<span class="LC_filename">'.
 8929:                                             $fname.'</span>').'</p>'; 
 8930:                     } else {
 8931:                          $output = '<p class="LC_error">'.
 8932:                                    &mt('Error: update failed for: [_1].',
 8933:                                    '<span class="LC_filename">'.
 8934:                                    $container.'</span>').'</p>';
 8935:                     }
 8936:                 } else {
 8937:                     if (open(my $fh,">$container")) {
 8938:                         print $fh $content;
 8939:                         close($fh);
 8940:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 8941:                                   $count,'<span class="LC_filename">'.
 8942:                                   $container.'</span>').'</p>';
 8943:                     } else {
 8944:                          $output = '<p class="LC_error">'.
 8945:                                    &mt('Error: could not update [_1].',
 8946:                                    '<span class="LC_filename">'.
 8947:                                    $container.'</span>').'</p>';
 8948:                     }
 8949:                 }
 8950:             }
 8951:         } else {
 8952:             &logthis('Failed to parse '.$container.
 8953:                      ' to modify references: '.$parse_result);
 8954:         }
 8955:     }
 8956:     return $output;
 8957: }
 8958: 
 8959: sub check_for_existing {
 8960:     my ($path,$fname,$element) = @_;
 8961:     my ($state,$msg);
 8962:     if (-d $path.'/'.$fname) {
 8963:         $state = 'exists';
 8964:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8965:     } elsif (-e $path.'/'.$fname) {
 8966:         $state = 'exists';
 8967:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8968:     }
 8969:     if ($state eq 'exists') {
 8970:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8971:     }
 8972:     return ($state,$msg);
 8973: }
 8974: 
 8975: sub check_for_upload {
 8976:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8977:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8978:     my $filesize = length($env{'form.'.$element});
 8979:     if (!$filesize) {
 8980:         my $msg = '<span class="LC_error">'.
 8981:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
 8982:                       '<span class="LC_filename">'.$fname.'</span>',
 8983:                       $filesize).'<br />'.
 8984:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
 8985:                   '</span>';
 8986:         return ('zero_bytes',$msg);
 8987:     }
 8988:     $filesize =  $filesize/1000; #express in k (1024?)
 8989:     my $getpropath = 1;
 8990:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8991:                                             $getpropath);
 8992:     my $found_file = 0;
 8993:     my $locked_file = 0;
 8994:     my @lockers;
 8995:     my $navmap;
 8996:     if ($env{'request.course.id'}) {
 8997:         $navmap = Apache::lonnavmaps::navmap->new();
 8998:     }
 8999:     foreach my $line (@dir_list) {
 9000:         my ($file_name,$rest)=split(/\&/,$line,2);
 9001:         if ($file_name eq $fname){
 9002:             $file_name = $path.$file_name;
 9003:             if ($group ne '') {
 9004:                 $file_name = $group.$file_name;
 9005:             }
 9006:             $found_file = 1;
 9007:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
 9008:                 foreach my $lock (@lockers) {
 9009:                     if (ref($lock) eq 'ARRAY') {
 9010:                         my ($symb,$crsid) = @{$lock};
 9011:                         if ($crsid eq $env{'request.course.id'}) {
 9012:                             if (ref($navmap)) {
 9013:                                 my $res = $navmap->getBySymb($symb);
 9014:                                 foreach my $part (@{$res->parts()}) { 
 9015:                                     my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
 9016:                                     unless (($slot_status == $res->RESERVED) ||
 9017:                                             ($slot_status == $res->RESERVED_LOCATION)) {
 9018:                                         $locked_file = 1;
 9019:                                     }
 9020:                                 }
 9021:                             } else {
 9022:                                 $locked_file = 1;
 9023:                             }
 9024:                         } else {
 9025:                             $locked_file = 1;
 9026:                         }
 9027:                     }
 9028:                 }
 9029:             } else {
 9030:                 my @info = split(/\&/,$rest);
 9031:                 my $currsize = $info[6]/1000;
 9032:                 if ($currsize < $filesize) {
 9033:                     my $extra = $filesize - $currsize;
 9034:                     if (($current_disk_usage + $extra) > $disk_quota) {
 9035:                         my $msg = '<span class="LC_error">'.
 9036:                                   &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.',
 9037:                                       '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
 9038:                                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9039:                                                $disk_quota,$current_disk_usage);
 9040:                         return ('will_exceed_quota',$msg);
 9041:                     }
 9042:                 }
 9043:             }
 9044:         }
 9045:     }
 9046:     if (($current_disk_usage + $filesize) > $disk_quota){
 9047:         my $msg = '<span class="LC_error">'.
 9048:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 9049:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 9050:         return ('will_exceed_quota',$msg);
 9051:     } elsif ($found_file) {
 9052:         if ($locked_file) {
 9053:             my $msg = '<span class="LC_error">';
 9054:             $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>');
 9055:             $msg .= '</span><br />';
 9056:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 9057:             return ('file_locked',$msg);
 9058:         } else {
 9059:             my $msg = '<span class="LC_error">';
 9060:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 9061:             $msg .= '</span>';
 9062:             return ('existingfile',$msg);
 9063:         }
 9064:     }
 9065: }
 9066: 
 9067: sub check_for_traversal {
 9068:     my ($path,$url,$toplevel) = @_;
 9069:     my @parts=split(/\//,$path);
 9070:     my $cleanpath;
 9071:     my $fullpath = $url;
 9072:     for (my $i=0;$i<@parts;$i++) {
 9073:         next if ($parts[$i] eq '.');
 9074:         if ($parts[$i] eq '..') {
 9075:             $fullpath =~ s{([^/]+/)$}{};
 9076:         } else {
 9077:             $fullpath .= $parts[$i].'/';
 9078:         }
 9079:     }
 9080:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
 9081:         $cleanpath = $1;
 9082:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
 9083:         my $curr_toprel = $1;
 9084:         my @parts = split(/\//,$curr_toprel);
 9085:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
 9086:         my @urlparts = split(/\//,$url_toprel);
 9087:         my $doubledots;
 9088:         my $startdiff = -1;
 9089:         for (my $i=0; $i<@urlparts; $i++) {
 9090:             if ($startdiff == -1) {
 9091:                 unless ($urlparts[$i] eq $parts[$i]) {
 9092:                     $startdiff = $i;
 9093:                     $doubledots .= '../';
 9094:                 }
 9095:             } else {
 9096:                 $doubledots .= '../';
 9097:             }
 9098:         }
 9099:         if ($startdiff > -1) {
 9100:             $cleanpath = $doubledots;
 9101:             for (my $i=$startdiff; $i<@parts; $i++) {
 9102:                 $cleanpath .= $parts[$i].'/';
 9103:             }
 9104:         }
 9105:     }
 9106:     $cleanpath =~ s{(/)$}{};
 9107:     return $cleanpath;
 9108: }
 9109: 
 9110: =pod
 9111: 
 9112: =back
 9113: 
 9114: =head1 CSV Upload/Handling functions
 9115: 
 9116: =over 4
 9117: 
 9118: =item * &upfile_store($r)
 9119: 
 9120: Store uploaded file, $r should be the HTTP Request object,
 9121: needs $env{'form.upfile'}
 9122: returns $datatoken to be put into hidden field
 9123: 
 9124: =cut
 9125: 
 9126: sub upfile_store {
 9127:     my $r=shift;
 9128:     $env{'form.upfile'}=~s/\r/\n/gs;
 9129:     $env{'form.upfile'}=~s/\f/\n/gs;
 9130:     $env{'form.upfile'}=~s/\n+/\n/gs;
 9131:     $env{'form.upfile'}=~s/\n+$//gs;
 9132: 
 9133:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 9134: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 9135:     {
 9136:         my $datafile = $r->dir_config('lonDaemons').
 9137:                            '/tmp/'.$datatoken.'.tmp';
 9138:         if ( open(my $fh,">$datafile") ) {
 9139:             print $fh $env{'form.upfile'};
 9140:             close($fh);
 9141:         }
 9142:     }
 9143:     return $datatoken;
 9144: }
 9145: 
 9146: =pod
 9147: 
 9148: =item * &load_tmp_file($r)
 9149: 
 9150: Load uploaded file from tmp, $r should be the HTTP Request object,
 9151: needs $env{'form.datatoken'},
 9152: sets $env{'form.upfile'} to the contents of the file
 9153: 
 9154: =cut
 9155: 
 9156: sub load_tmp_file {
 9157:     my $r=shift;
 9158:     my @studentdata=();
 9159:     {
 9160:         my $studentfile = $r->dir_config('lonDaemons').
 9161:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 9162:         if ( open(my $fh,"<$studentfile") ) {
 9163:             @studentdata=<$fh>;
 9164:             close($fh);
 9165:         }
 9166:     }
 9167:     $env{'form.upfile'}=join('',@studentdata);
 9168: }
 9169: 
 9170: =pod
 9171: 
 9172: =item * &upfile_record_sep()
 9173: 
 9174: Separate uploaded file into records
 9175: returns array of records,
 9176: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 9177: 
 9178: =cut
 9179: 
 9180: sub upfile_record_sep {
 9181:     if ($env{'form.upfiletype'} eq 'xml') {
 9182:     } else {
 9183: 	my @records;
 9184: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 9185: 	    if ($line=~/^\s*$/) { next; }
 9186: 	    push(@records,$line);
 9187: 	}
 9188: 	return @records;
 9189:     }
 9190: }
 9191: 
 9192: =pod
 9193: 
 9194: =item * &record_sep($record)
 9195: 
 9196: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 9197: 
 9198: =cut
 9199: 
 9200: sub takeleft {
 9201:     my $index=shift;
 9202:     return substr('0000'.$index,-4,4);
 9203: }
 9204: 
 9205: sub record_sep {
 9206:     my $record=shift;
 9207:     my %components=();
 9208:     if ($env{'form.upfiletype'} eq 'xml') {
 9209:     } elsif ($env{'form.upfiletype'} eq 'space') {
 9210:         my $i=0;
 9211:         foreach my $field (split(/\s+/,$record)) {
 9212:             $field=~s/^(\"|\')//;
 9213:             $field=~s/(\"|\')$//;
 9214:             $components{&takeleft($i)}=$field;
 9215:             $i++;
 9216:         }
 9217:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 9218:         my $i=0;
 9219:         foreach my $field (split(/\t/,$record)) {
 9220:             $field=~s/^(\"|\')//;
 9221:             $field=~s/(\"|\')$//;
 9222:             $components{&takeleft($i)}=$field;
 9223:             $i++;
 9224:         }
 9225:     } else {
 9226:         my $separator=',';
 9227:         if ($env{'form.upfiletype'} eq 'semisv') {
 9228:             $separator=';';
 9229:         }
 9230:         my $i=0;
 9231: # the character we are looking for to indicate the end of a quote or a record 
 9232:         my $looking_for=$separator;
 9233: # do not add the characters to the fields
 9234:         my $ignore=0;
 9235: # we just encountered a separator (or the beginning of the record)
 9236:         my $just_found_separator=1;
 9237: # store the field we are working on here
 9238:         my $field='';
 9239: # work our way through all characters in record
 9240:         foreach my $character ($record=~/(.)/g) {
 9241:             if ($character eq $looking_for) {
 9242:                if ($character ne $separator) {
 9243: # Found the end of a quote, again looking for separator
 9244:                   $looking_for=$separator;
 9245:                   $ignore=1;
 9246:                } else {
 9247: # Found a separator, store away what we got
 9248:                   $components{&takeleft($i)}=$field;
 9249: 	          $i++;
 9250:                   $just_found_separator=1;
 9251:                   $ignore=0;
 9252:                   $field='';
 9253:                }
 9254:                next;
 9255:             }
 9256: # single or double quotation marks after a separator indicate beginning of a quote
 9257: # we are now looking for the end of the quote and need to ignore separators
 9258:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 9259:                $looking_for=$character;
 9260:                next;
 9261:             }
 9262: # ignore would be true after we reached the end of a quote
 9263:             if ($ignore) { next; }
 9264:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 9265:             $field.=$character;
 9266:             $just_found_separator=0; 
 9267:         }
 9268: # catch the very last entry, since we never encountered the separator
 9269:         $components{&takeleft($i)}=$field;
 9270:     }
 9271:     return %components;
 9272: }
 9273: 
 9274: ######################################################
 9275: ######################################################
 9276: 
 9277: =pod
 9278: 
 9279: =item * &upfile_select_html()
 9280: 
 9281: Return HTML code to select a file from the users machine and specify 
 9282: the file type.
 9283: 
 9284: =cut
 9285: 
 9286: ######################################################
 9287: ######################################################
 9288: sub upfile_select_html {
 9289:     my %Types = (
 9290:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 9291:                  semisv => &mt('Semicolon separated values'),
 9292:                  space => &mt('Space separated'),
 9293:                  tab   => &mt('Tabulator separated'),
 9294: #                 xml   => &mt('HTML/XML'),
 9295:                  );
 9296:     my $Str = '<input type="file" name="upfile" size="50" />'.
 9297:         '<br />'.&mt('Type').': <select name="upfiletype">';
 9298:     foreach my $type (sort(keys(%Types))) {
 9299:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 9300:     }
 9301:     $Str .= "</select>\n";
 9302:     return $Str;
 9303: }
 9304: 
 9305: sub get_samples {
 9306:     my ($records,$toget) = @_;
 9307:     my @samples=({});
 9308:     my $got=0;
 9309:     foreach my $rec (@$records) {
 9310: 	my %temp = &record_sep($rec);
 9311: 	if (! grep(/\S/, values(%temp))) { next; }
 9312: 	if (%temp) {
 9313: 	    $samples[$got]=\%temp;
 9314: 	    $got++;
 9315: 	    if ($got == $toget) { last; }
 9316: 	}
 9317:     }
 9318:     return \@samples;
 9319: }
 9320: 
 9321: ######################################################
 9322: ######################################################
 9323: 
 9324: =pod
 9325: 
 9326: =item * &csv_print_samples($r,$records)
 9327: 
 9328: Prints a table of sample values from each column uploaded $r is an
 9329: Apache Request ref, $records is an arrayref from
 9330: &Apache::loncommon::upfile_record_sep
 9331: 
 9332: =cut
 9333: 
 9334: ######################################################
 9335: ######################################################
 9336: sub csv_print_samples {
 9337:     my ($r,$records) = @_;
 9338:     my $samples = &get_samples($records,5);
 9339: 
 9340:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 9341:               &start_data_table_header_row());
 9342:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 9343:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 9344:     $r->print(&end_data_table_header_row());
 9345:     foreach my $hash (@$samples) {
 9346: 	$r->print(&start_data_table_row());
 9347: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9348: 	    $r->print('<td>');
 9349: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 9350: 	    $r->print('</td>');
 9351: 	}
 9352: 	$r->print(&end_data_table_row());
 9353:     }
 9354:     $r->print(&end_data_table().'<br />'."\n");
 9355: }
 9356: 
 9357: ######################################################
 9358: ######################################################
 9359: 
 9360: =pod
 9361: 
 9362: =item * &csv_print_select_table($r,$records,$d)
 9363: 
 9364: Prints a table to create associations between values and table columns.
 9365: 
 9366: $r is an Apache Request ref,
 9367: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9368: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 9369: 
 9370: =cut
 9371: 
 9372: ######################################################
 9373: ######################################################
 9374: sub csv_print_select_table {
 9375:     my ($r,$records,$d) = @_;
 9376:     my $i=0;
 9377:     my $samples = &get_samples($records,1);
 9378:     $r->print(&mt('Associate columns with student attributes.')."\n".
 9379: 	      &start_data_table().&start_data_table_header_row().
 9380:               '<th>'.&mt('Attribute').'</th>'.
 9381:               '<th>'.&mt('Column').'</th>'.
 9382:               &end_data_table_header_row()."\n");
 9383:     foreach my $array_ref (@$d) {
 9384: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 9385: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 9386: 
 9387: 	$r->print('<td><select name="f'.$i.'"'.
 9388: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9389: 	$r->print('<option value="none"></option>');
 9390: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9391: 	    $r->print('<option value="'.$sample.'"'.
 9392:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 9393:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 9394: 	}
 9395: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 9396: 	$i++;
 9397:     }
 9398:     $r->print(&end_data_table());
 9399:     $i--;
 9400:     return $i;
 9401: }
 9402: 
 9403: ######################################################
 9404: ######################################################
 9405: 
 9406: =pod
 9407: 
 9408: =item * &csv_samples_select_table($r,$records,$d)
 9409: 
 9410: Prints a table of sample values from the upload and can make associate samples to internal names.
 9411: 
 9412: $r is an Apache Request ref,
 9413: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9414: $d is an array of 2 element arrays (internal name, displayed name)
 9415: 
 9416: =cut
 9417: 
 9418: ######################################################
 9419: ######################################################
 9420: sub csv_samples_select_table {
 9421:     my ($r,$records,$d) = @_;
 9422:     my $i=0;
 9423:     #
 9424:     my $max_samples = 5;
 9425:     my $samples = &get_samples($records,$max_samples);
 9426:     $r->print(&start_data_table().
 9427:               &start_data_table_header_row().'<th>'.
 9428:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 9429:               &end_data_table_header_row());
 9430: 
 9431:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 9432: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 9433: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9434: 	foreach my $option (@$d) {
 9435: 	    my ($value,$display,$defaultcol)=@{ $option };
 9436: 	    $r->print('<option value="'.$value.'"'.
 9437:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 9438:                       $display.'</option>');
 9439: 	}
 9440: 	$r->print('</select></td><td>');
 9441: 	foreach my $line (0..($max_samples-1)) {
 9442: 	    if (defined($samples->[$line]{$key})) { 
 9443: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 9444: 	    }
 9445: 	}
 9446: 	$r->print('</td>'.&end_data_table_row());
 9447: 	$i++;
 9448:     }
 9449:     $r->print(&end_data_table());
 9450:     $i--;
 9451:     return($i);
 9452: }
 9453: 
 9454: ######################################################
 9455: ######################################################
 9456: 
 9457: =pod
 9458: 
 9459: =item * &clean_excel_name($name)
 9460: 
 9461: Returns a replacement for $name which does not contain any illegal characters.
 9462: 
 9463: =cut
 9464: 
 9465: ######################################################
 9466: ######################################################
 9467: sub clean_excel_name {
 9468:     my ($name) = @_;
 9469:     $name =~ s/[:\*\?\/\\]//g;
 9470:     if (length($name) > 31) {
 9471:         $name = substr($name,0,31);
 9472:     }
 9473:     return $name;
 9474: }
 9475: 
 9476: =pod
 9477: 
 9478: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 9479: 
 9480: Returns either 1 or undef
 9481: 
 9482: 1 if the part is to be hidden, undef if it is to be shown
 9483: 
 9484: Arguments are:
 9485: 
 9486: $id the id of the part to be checked
 9487: $symb, optional the symb of the resource to check
 9488: $udom, optional the domain of the user to check for
 9489: $uname, optional the username of the user to check for
 9490: 
 9491: =cut
 9492: 
 9493: sub check_if_partid_hidden {
 9494:     my ($id,$symb,$udom,$uname) = @_;
 9495:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 9496: 					 $symb,$udom,$uname);
 9497:     my $truth=1;
 9498:     #if the string starts with !, then the list is the list to show not hide
 9499:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 9500:     my @hiddenlist=split(/,/,$hiddenparts);
 9501:     foreach my $checkid (@hiddenlist) {
 9502: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 9503:     }
 9504:     return !$truth;
 9505: }
 9506: 
 9507: 
 9508: ############################################################
 9509: ############################################################
 9510: 
 9511: =pod
 9512: 
 9513: =back 
 9514: 
 9515: =head1 cgi-bin script and graphing routines
 9516: 
 9517: =over 4
 9518: 
 9519: =item * &get_cgi_id()
 9520: 
 9521: Inputs: none
 9522: 
 9523: Returns an id which can be used to pass environment variables
 9524: to various cgi-bin scripts.  These environment variables will
 9525: be removed from the users environment after a given time by
 9526: the routine &Apache::lonnet::transfer_profile_to_env.
 9527: 
 9528: =cut
 9529: 
 9530: ############################################################
 9531: ############################################################
 9532: my $uniq=0;
 9533: sub get_cgi_id {
 9534:     $uniq=($uniq+1)%100000;
 9535:     return (time.'_'.$$.'_'.$uniq);
 9536: }
 9537: 
 9538: ############################################################
 9539: ############################################################
 9540: 
 9541: =pod
 9542: 
 9543: =item * &DrawBarGraph()
 9544: 
 9545: Facilitates the plotting of data in a (stacked) bar graph.
 9546: Puts plot definition data into the users environment in order for 
 9547: graph.png to plot it.  Returns an <img> tag for the plot.
 9548: The bars on the plot are labeled '1','2',...,'n'.
 9549: 
 9550: Inputs:
 9551: 
 9552: =over 4
 9553: 
 9554: =item $Title: string, the title of the plot
 9555: 
 9556: =item $xlabel: string, text describing the X-axis of the plot
 9557: 
 9558: =item $ylabel: string, text describing the Y-axis of the plot
 9559: 
 9560: =item $Max: scalar, the maximum Y value to use in the plot
 9561: If $Max is < any data point, the graph will not be rendered.
 9562: 
 9563: =item $colors: array ref holding the colors to be used for the data sets when
 9564: they are plotted.  If undefined, default values will be used.
 9565: 
 9566: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 9567: 
 9568: =item @Values: An array of array references.  Each array reference holds data
 9569: to be plotted in a stacked bar chart.
 9570: 
 9571: =item If the final element of @Values is a hash reference the key/value
 9572: pairs will be added to the graph definition.
 9573: 
 9574: =back
 9575: 
 9576: Returns:
 9577: 
 9578: An <img> tag which references graph.png and the appropriate identifying
 9579: information for the plot.
 9580: 
 9581: =cut
 9582: 
 9583: ############################################################
 9584: ############################################################
 9585: sub DrawBarGraph {
 9586:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9587:     #
 9588:     if (! defined($colors)) {
 9589:         $colors = ['#33ff00', 
 9590:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9591:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9592:                   ]; 
 9593:     }
 9594:     my $extra_settings = {};
 9595:     if (ref($Values[-1]) eq 'HASH') {
 9596:         $extra_settings = pop(@Values);
 9597:     }
 9598:     #
 9599:     my $identifier = &get_cgi_id();
 9600:     my $id = 'cgi.'.$identifier;        
 9601:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9602:         return '';
 9603:     }
 9604:     #
 9605:     my @Labels;
 9606:     if (defined($labels)) {
 9607:         @Labels = @$labels;
 9608:     } else {
 9609:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9610:             push (@Labels,$i+1);
 9611:         }
 9612:     }
 9613:     #
 9614:     my $NumBars = scalar(@{$Values[0]});
 9615:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9616:     my %ValuesHash;
 9617:     my $NumSets=1;
 9618:     foreach my $array (@Values) {
 9619:         next if (! ref($array));
 9620:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9621:             join(',',@$array);
 9622:     }
 9623:     #
 9624:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9625:     if ($NumBars < 3) {
 9626:         $width = 120+$NumBars*32;
 9627:         $xskip = 1;
 9628:         $bar_width = 30;
 9629:     } elsif ($NumBars < 5) {
 9630:         $width = 120+$NumBars*20;
 9631:         $xskip = 1;
 9632:         $bar_width = 20;
 9633:     } elsif ($NumBars < 10) {
 9634:         $width = 120+$NumBars*15;
 9635:         $xskip = 1;
 9636:         $bar_width = 15;
 9637:     } elsif ($NumBars <= 25) {
 9638:         $width = 120+$NumBars*11;
 9639:         $xskip = 5;
 9640:         $bar_width = 8;
 9641:     } elsif ($NumBars <= 50) {
 9642:         $width = 120+$NumBars*8;
 9643:         $xskip = 5;
 9644:         $bar_width = 4;
 9645:     } else {
 9646:         $width = 120+$NumBars*8;
 9647:         $xskip = 5;
 9648:         $bar_width = 4;
 9649:     }
 9650:     #
 9651:     $Max = 1 if ($Max < 1);
 9652:     if ( int($Max) < $Max ) {
 9653:         $Max++;
 9654:         $Max = int($Max);
 9655:     }
 9656:     $Title  = '' if (! defined($Title));
 9657:     $xlabel = '' if (! defined($xlabel));
 9658:     $ylabel = '' if (! defined($ylabel));
 9659:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9660:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9661:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9662:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9663:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9664:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9665:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9666:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9667:     $ValuesHash{$id.'.height'}   = $height;
 9668:     $ValuesHash{$id.'.width'}    = $width;
 9669:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9670:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 9671:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 9672:     #
 9673:     # Deal with other parameters
 9674:     while (my ($key,$value) = each(%$extra_settings)) {
 9675:         $ValuesHash{$id.'.'.$key} = $value;
 9676:     }
 9677:     #
 9678:     &Apache::lonnet::appenv(\%ValuesHash);
 9679:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9680: }
 9681: 
 9682: ############################################################
 9683: ############################################################
 9684: 
 9685: =pod
 9686: 
 9687: =item * &DrawXYGraph()
 9688: 
 9689: Facilitates the plotting of data in an XY graph.
 9690: Puts plot definition data into the users environment in order for 
 9691: graph.png to plot it.  Returns an <img> tag for the plot.
 9692: 
 9693: Inputs:
 9694: 
 9695: =over 4
 9696: 
 9697: =item $Title: string, the title of the plot
 9698: 
 9699: =item $xlabel: string, text describing the X-axis of the plot
 9700: 
 9701: =item $ylabel: string, text describing the Y-axis of the plot
 9702: 
 9703: =item $Max: scalar, the maximum Y value to use in the plot
 9704: If $Max is < any data point, the graph will not be rendered.
 9705: 
 9706: =item $colors: Array ref containing the hex color codes for the data to be 
 9707: plotted in.  If undefined, default values will be used.
 9708: 
 9709: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9710: 
 9711: =item $Ydata: Array ref containing Array refs.  
 9712: Each of the contained arrays will be plotted as a separate curve.
 9713: 
 9714: =item %Values: hash indicating or overriding any default values which are 
 9715: passed to graph.png.  
 9716: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9717: 
 9718: =back
 9719: 
 9720: Returns:
 9721: 
 9722: An <img> tag which references graph.png and the appropriate identifying
 9723: information for the plot.
 9724: 
 9725: =cut
 9726: 
 9727: ############################################################
 9728: ############################################################
 9729: sub DrawXYGraph {
 9730:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9731:     #
 9732:     # Create the identifier for the graph
 9733:     my $identifier = &get_cgi_id();
 9734:     my $id = 'cgi.'.$identifier;
 9735:     #
 9736:     $Title  = '' if (! defined($Title));
 9737:     $xlabel = '' if (! defined($xlabel));
 9738:     $ylabel = '' if (! defined($ylabel));
 9739:     my %ValuesHash = 
 9740:         (
 9741:          $id.'.title'  => &escape($Title),
 9742:          $id.'.xlabel' => &escape($xlabel),
 9743:          $id.'.ylabel' => &escape($ylabel),
 9744:          $id.'.y_max_value'=> $Max,
 9745:          $id.'.labels'     => join(',',@$Xlabels),
 9746:          $id.'.PlotType'   => 'XY',
 9747:          );
 9748:     #
 9749:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9750:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9751:     }
 9752:     #
 9753:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9754:         return '';
 9755:     }
 9756:     my $NumSets=1;
 9757:     foreach my $array (@{$Ydata}){
 9758:         next if (! ref($array));
 9759:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9760:     }
 9761:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9762:     #
 9763:     # Deal with other parameters
 9764:     while (my ($key,$value) = each(%Values)) {
 9765:         $ValuesHash{$id.'.'.$key} = $value;
 9766:     }
 9767:     #
 9768:     &Apache::lonnet::appenv(\%ValuesHash);
 9769:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9770: }
 9771: 
 9772: ############################################################
 9773: ############################################################
 9774: 
 9775: =pod
 9776: 
 9777: =item * &DrawXYYGraph()
 9778: 
 9779: Facilitates the plotting of data in an XY graph with two Y axes.
 9780: Puts plot definition data into the users environment in order for 
 9781: graph.png to plot it.  Returns an <img> tag for the plot.
 9782: 
 9783: Inputs:
 9784: 
 9785: =over 4
 9786: 
 9787: =item $Title: string, the title of the plot
 9788: 
 9789: =item $xlabel: string, text describing the X-axis of the plot
 9790: 
 9791: =item $ylabel: string, text describing the Y-axis of the plot
 9792: 
 9793: =item $colors: Array ref containing the hex color codes for the data to be 
 9794: plotted in.  If undefined, default values will be used.
 9795: 
 9796: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9797: 
 9798: =item $Ydata1: The first data set
 9799: 
 9800: =item $Min1: The minimum value of the left Y-axis
 9801: 
 9802: =item $Max1: The maximum value of the left Y-axis
 9803: 
 9804: =item $Ydata2: The second data set
 9805: 
 9806: =item $Min2: The minimum value of the right Y-axis
 9807: 
 9808: =item $Max2: The maximum value of the left Y-axis
 9809: 
 9810: =item %Values: hash indicating or overriding any default values which are 
 9811: passed to graph.png.  
 9812: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9813: 
 9814: =back
 9815: 
 9816: Returns:
 9817: 
 9818: An <img> tag which references graph.png and the appropriate identifying
 9819: information for the plot.
 9820: 
 9821: =cut
 9822: 
 9823: ############################################################
 9824: ############################################################
 9825: sub DrawXYYGraph {
 9826:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9827:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9828:     #
 9829:     # Create the identifier for the graph
 9830:     my $identifier = &get_cgi_id();
 9831:     my $id = 'cgi.'.$identifier;
 9832:     #
 9833:     $Title  = '' if (! defined($Title));
 9834:     $xlabel = '' if (! defined($xlabel));
 9835:     $ylabel = '' if (! defined($ylabel));
 9836:     my %ValuesHash = 
 9837:         (
 9838:          $id.'.title'  => &escape($Title),
 9839:          $id.'.xlabel' => &escape($xlabel),
 9840:          $id.'.ylabel' => &escape($ylabel),
 9841:          $id.'.labels' => join(',',@$Xlabels),
 9842:          $id.'.PlotType' => 'XY',
 9843:          $id.'.NumSets' => 2,
 9844:          $id.'.two_axes' => 1,
 9845:          $id.'.y1_max_value' => $Max1,
 9846:          $id.'.y1_min_value' => $Min1,
 9847:          $id.'.y2_max_value' => $Max2,
 9848:          $id.'.y2_min_value' => $Min2,
 9849:          );
 9850:     #
 9851:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9852:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9853:     }
 9854:     #
 9855:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9856:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9857:         return '';
 9858:     }
 9859:     my $NumSets=1;
 9860:     foreach my $array ($Ydata1,$Ydata2){
 9861:         next if (! ref($array));
 9862:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9863:     }
 9864:     #
 9865:     # Deal with other parameters
 9866:     while (my ($key,$value) = each(%Values)) {
 9867:         $ValuesHash{$id.'.'.$key} = $value;
 9868:     }
 9869:     #
 9870:     &Apache::lonnet::appenv(\%ValuesHash);
 9871:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9872: }
 9873: 
 9874: ############################################################
 9875: ############################################################
 9876: 
 9877: =pod
 9878: 
 9879: =back 
 9880: 
 9881: =head1 Statistics helper routines?  
 9882: 
 9883: Bad place for them but what the hell.
 9884: 
 9885: =over 4
 9886: 
 9887: =item * &chartlink()
 9888: 
 9889: Returns a link to the chart for a specific student.  
 9890: 
 9891: Inputs:
 9892: 
 9893: =over 4
 9894: 
 9895: =item $linktext: The text of the link
 9896: 
 9897: =item $sname: The students username
 9898: 
 9899: =item $sdomain: The students domain
 9900: 
 9901: =back
 9902: 
 9903: =back
 9904: 
 9905: =cut
 9906: 
 9907: ############################################################
 9908: ############################################################
 9909: sub chartlink {
 9910:     my ($linktext, $sname, $sdomain) = @_;
 9911:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9912:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9913:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9914:        '">'.$linktext.'</a>';
 9915: }
 9916: 
 9917: #######################################################
 9918: #######################################################
 9919: 
 9920: =pod
 9921: 
 9922: =head1 Course Environment Routines
 9923: 
 9924: =over 4
 9925: 
 9926: =item * &restore_course_settings()
 9927: 
 9928: =item * &store_course_settings()
 9929: 
 9930: Restores/Store indicated form parameters from the course environment.
 9931: Will not overwrite existing values of the form parameters.
 9932: 
 9933: Inputs: 
 9934: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9935: 
 9936: a hash ref describing the data to be stored.  For example:
 9937:    
 9938: %Save_Parameters = ('Status' => 'scalar',
 9939:     'chartoutputmode' => 'scalar',
 9940:     'chartoutputdata' => 'scalar',
 9941:     'Section' => 'array',
 9942:     'Group' => 'array',
 9943:     'StudentData' => 'array',
 9944:     'Maps' => 'array');
 9945: 
 9946: Returns: both routines return nothing
 9947: 
 9948: =back
 9949: 
 9950: =cut
 9951: 
 9952: #######################################################
 9953: #######################################################
 9954: sub store_course_settings {
 9955:     return &store_settings($env{'request.course.id'},@_);
 9956: }
 9957: 
 9958: sub store_settings {
 9959:     # save to the environment
 9960:     # appenv the same items, just to be safe
 9961:     my $udom  = $env{'user.domain'};
 9962:     my $uname = $env{'user.name'};
 9963:     my ($context,$prefix,$Settings) = @_;
 9964:     my %SaveHash;
 9965:     my %AppHash;
 9966:     while (my ($setting,$type) = each(%$Settings)) {
 9967:         my $basename = join('.','internal',$context,$prefix,$setting);
 9968:         my $envname = 'environment.'.$basename;
 9969:         if (exists($env{'form.'.$setting})) {
 9970:             # Save this value away
 9971:             if ($type eq 'scalar' &&
 9972:                 (! exists($env{$envname}) || 
 9973:                  $env{$envname} ne $env{'form.'.$setting})) {
 9974:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9975:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9976:             } elsif ($type eq 'array') {
 9977:                 my $stored_form;
 9978:                 if (ref($env{'form.'.$setting})) {
 9979:                     $stored_form = join(',',
 9980:                                         map {
 9981:                                             &escape($_);
 9982:                                         } sort(@{$env{'form.'.$setting}}));
 9983:                 } else {
 9984:                     $stored_form = 
 9985:                         &escape($env{'form.'.$setting});
 9986:                 }
 9987:                 # Determine if the array contents are the same.
 9988:                 if ($stored_form ne $env{$envname}) {
 9989:                     $SaveHash{$basename} = $stored_form;
 9990:                     $AppHash{$envname}   = $stored_form;
 9991:                 }
 9992:             }
 9993:         }
 9994:     }
 9995:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9996:                                           $udom,$uname);
 9997:     if ($put_result !~ /^(ok|delayed)/) {
 9998:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9999:                                  'got error:'.$put_result);
10000:     }
10001:     # Make sure these settings stick around in this session, too
10002:     &Apache::lonnet::appenv(\%AppHash);
10003:     return;
10004: }
10005: 
10006: sub restore_course_settings {
10007:     return &restore_settings($env{'request.course.id'},@_);
10008: }
10009: 
10010: sub restore_settings {
10011:     my ($context,$prefix,$Settings) = @_;
10012:     while (my ($setting,$type) = each(%$Settings)) {
10013:         next if (exists($env{'form.'.$setting}));
10014:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
10015:             '.'.$setting;
10016:         if (exists($env{$envname})) {
10017:             if ($type eq 'scalar') {
10018:                 $env{'form.'.$setting} = $env{$envname};
10019:             } elsif ($type eq 'array') {
10020:                 $env{'form.'.$setting} = [ 
10021:                                            map { 
10022:                                                &unescape($_); 
10023:                                            } split(',',$env{$envname})
10024:                                            ];
10025:             }
10026:         }
10027:     }
10028: }
10029: 
10030: #######################################################
10031: #######################################################
10032: 
10033: =pod
10034: 
10035: =head1 Domain E-mail Routines  
10036: 
10037: =over 4
10038: 
10039: =item * &build_recipient_list()
10040: 
10041: Build recipient lists for five types of e-mail:
10042: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
10043: (d) Help requests, (e) Course requests needing approval,  generated by
10044: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
10045: loncoursequeueadmin.pm respectively.
10046: 
10047: Inputs:
10048: defmail (scalar - email address of default recipient), 
10049: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
10050: defdom (domain for which to retrieve configuration settings),
10051: origmail (scalar - email address of recipient from loncapa.conf, 
10052: i.e., predates configuration by DC via domainprefs.pm 
10053: 
10054: Returns: comma separated list of addresses to which to send e-mail.
10055: 
10056: =back
10057: 
10058: =cut
10059: 
10060: ############################################################
10061: ############################################################
10062: sub build_recipient_list {
10063:     my ($defmail,$mailing,$defdom,$origmail) = @_;
10064:     my @recipients;
10065:     my $otheremails;
10066:     my %domconfig =
10067:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
10068:     if (ref($domconfig{'contacts'}) eq 'HASH') {
10069:         if (exists($domconfig{'contacts'}{$mailing})) {
10070:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
10071:                 my @contacts = ('adminemail','supportemail');
10072:                 foreach my $item (@contacts) {
10073:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
10074:                         my $addr = $domconfig{'contacts'}{$item}; 
10075:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
10076:                             push(@recipients,$addr);
10077:                         }
10078:                     }
10079:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
10080:                 }
10081:             }
10082:         } elsif ($origmail ne '') {
10083:             push(@recipients,$origmail);
10084:         }
10085:     } elsif ($origmail ne '') {
10086:         push(@recipients,$origmail);
10087:     }
10088:     if (defined($defmail)) {
10089:         if ($defmail ne '') {
10090:             push(@recipients,$defmail);
10091:         }
10092:     }
10093:     if ($otheremails) {
10094:         my @others;
10095:         if ($otheremails =~ /,/) {
10096:             @others = split(/,/,$otheremails);
10097:         } else {
10098:             push(@others,$otheremails);
10099:         }
10100:         foreach my $addr (@others) {
10101:             if (!grep(/^\Q$addr\E$/,@recipients)) {
10102:                 push(@recipients,$addr);
10103:             }
10104:         }
10105:     }
10106:     my $recipientlist = join(',',@recipients); 
10107:     return $recipientlist;
10108: }
10109: 
10110: ############################################################
10111: ############################################################
10112: 
10113: =pod
10114: 
10115: =head1 Course Catalog Routines
10116: 
10117: =over 4
10118: 
10119: =item * &gather_categories()
10120: 
10121: Converts category definitions - keys of categories hash stored in  
10122: coursecategories in configuration.db on the primary library server in a 
10123: domain - to an array.  Also generates javascript and idx hash used to 
10124: generate Domain Coordinator interface for editing Course Categories.
10125: 
10126: Inputs:
10127: 
10128: categories (reference to hash of category definitions).
10129: 
10130: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10131:       categories and subcategories).
10132: 
10133: idx (reference to hash of counters used in Domain Coordinator interface for 
10134:       editing Course Categories).
10135: 
10136: jsarray (reference to array of categories used to create Javascript arrays for
10137:          Domain Coordinator interface for editing Course Categories).
10138: 
10139: Returns: nothing
10140: 
10141: Side effects: populates cats, idx and jsarray. 
10142: 
10143: =cut
10144: 
10145: sub gather_categories {
10146:     my ($categories,$cats,$idx,$jsarray) = @_;
10147:     my %counters;
10148:     my $num = 0;
10149:     foreach my $item (keys(%{$categories})) {
10150:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10151:         if ($container eq '' && $depth == 0) {
10152:             $cats->[$depth][$categories->{$item}] = $cat;
10153:         } else {
10154:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
10155:         }
10156:         my ($escitem,$tail) = split(/:/,$item,2);
10157:         if ($counters{$tail} eq '') {
10158:             $counters{$tail} = $num;
10159:             $num ++;
10160:         }
10161:         if (ref($idx) eq 'HASH') {
10162:             $idx->{$item} = $counters{$tail};
10163:         }
10164:         if (ref($jsarray) eq 'ARRAY') {
10165:             push(@{$jsarray->[$counters{$tail}]},$item);
10166:         }
10167:     }
10168:     return;
10169: }
10170: 
10171: =pod
10172: 
10173: =item * &extract_categories()
10174: 
10175: Used to generate breadcrumb trails for course categories.
10176: 
10177: Inputs:
10178: 
10179: categories (reference to hash of category definitions).
10180: 
10181: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10182:       categories and subcategories).
10183: 
10184: trails (reference to array of breacrumb trails for each category).
10185: 
10186: allitems (reference to hash - key is category key 
10187:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10188: 
10189: idx (reference to hash of counters used in Domain Coordinator interface for
10190:       editing Course Categories).
10191: 
10192: jsarray (reference to array of categories used to create Javascript arrays for
10193:          Domain Coordinator interface for editing Course Categories).
10194: 
10195: subcats (reference to hash of arrays containing all subcategories within each 
10196:          category, -recursive)
10197: 
10198: Returns: nothing
10199: 
10200: Side effects: populates trails and allitems hash references.
10201: 
10202: =cut
10203: 
10204: sub extract_categories {
10205:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
10206:     if (ref($categories) eq 'HASH') {
10207:         &gather_categories($categories,$cats,$idx,$jsarray);
10208:         if (ref($cats->[0]) eq 'ARRAY') {
10209:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
10210:                 my $name = $cats->[0][$i];
10211:                 my $item = &escape($name).'::0';
10212:                 my $trailstr;
10213:                 if ($name eq 'instcode') {
10214:                     $trailstr = &mt('Official courses (with institutional codes)');
10215:                 } elsif ($name eq 'communities') {
10216:                     $trailstr = &mt('Communities');
10217:                 } else {
10218:                     $trailstr = $name;
10219:                 }
10220:                 if ($allitems->{$item} eq '') {
10221:                     push(@{$trails},$trailstr);
10222:                     $allitems->{$item} = scalar(@{$trails})-1;
10223:                 }
10224:                 my @parents = ($name);
10225:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
10226:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
10227:                         my $category = $cats->[1]{$name}[$j];
10228:                         if (ref($subcats) eq 'HASH') {
10229:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
10230:                         }
10231:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
10232:                     }
10233:                 } else {
10234:                     if (ref($subcats) eq 'HASH') {
10235:                         $subcats->{$item} = [];
10236:                     }
10237:                 }
10238:             }
10239:         }
10240:     }
10241:     return;
10242: }
10243: 
10244: =pod
10245: 
10246: =item *&recurse_categories()
10247: 
10248: Recursively used to generate breadcrumb trails for course categories.
10249: 
10250: Inputs:
10251: 
10252: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10253:       categories and subcategories).
10254: 
10255: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
10256: 
10257: category (current course category, for which breadcrumb trail is being generated).
10258: 
10259: trails (reference to array of breadcrumb trails for each category).
10260: 
10261: allitems (reference to hash - key is category key
10262:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10263: 
10264: parents (array containing containers directories for current category, 
10265:          back to top level). 
10266: 
10267: Returns: nothing
10268: 
10269: Side effects: populates trails and allitems hash references
10270: 
10271: =cut
10272: 
10273: sub recurse_categories {
10274:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
10275:     my $shallower = $depth - 1;
10276:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
10277:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
10278:             my $name = $cats->[$depth]{$category}[$k];
10279:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10280:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
10281:             if ($allitems->{$item} eq '') {
10282:                 push(@{$trails},$trailstr);
10283:                 $allitems->{$item} = scalar(@{$trails})-1;
10284:             }
10285:             my $deeper = $depth+1;
10286:             push(@{$parents},$category);
10287:             if (ref($subcats) eq 'HASH') {
10288:                 my $subcat = &escape($name).':'.$category.':'.$depth;
10289:                 for (my $j=@{$parents}; $j>=0; $j--) {
10290:                     my $higher;
10291:                     if ($j > 0) {
10292:                         $higher = &escape($parents->[$j]).':'.
10293:                                   &escape($parents->[$j-1]).':'.$j;
10294:                     } else {
10295:                         $higher = &escape($parents->[$j]).'::'.$j;
10296:                     }
10297:                     push(@{$subcats->{$higher}},$subcat);
10298:                 }
10299:             }
10300:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
10301:                                 $subcats);
10302:             pop(@{$parents});
10303:         }
10304:     } else {
10305:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10306:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
10307:         if ($allitems->{$item} eq '') {
10308:             push(@{$trails},$trailstr);
10309:             $allitems->{$item} = scalar(@{$trails})-1;
10310:         }
10311:     }
10312:     return;
10313: }
10314: 
10315: =pod
10316: 
10317: =item *&assign_categories_table()
10318: 
10319: Create a datatable for display of hierarchical categories in a domain,
10320: with checkboxes to allow a course to be categorized. 
10321: 
10322: Inputs:
10323: 
10324: cathash - reference to hash of categories defined for the domain (from
10325:           configuration.db)
10326: 
10327: currcat - scalar with an & separated list of categories assigned to a course. 
10328: 
10329: type    - scalar contains course type (Course or Community).
10330: 
10331: Returns: $output (markup to be displayed) 
10332: 
10333: =cut
10334: 
10335: sub assign_categories_table {
10336:     my ($cathash,$currcat,$type) = @_;
10337:     my $output;
10338:     if (ref($cathash) eq 'HASH') {
10339:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
10340:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
10341:         $maxdepth = scalar(@cats);
10342:         if (@cats > 0) {
10343:             my $itemcount = 0;
10344:             if (ref($cats[0]) eq 'ARRAY') {
10345:                 my @currcategories;
10346:                 if ($currcat ne '') {
10347:                     @currcategories = split('&',$currcat);
10348:                 }
10349:                 my $table;
10350:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
10351:                     my $parent = $cats[0][$i];
10352:                     next if ($parent eq 'instcode');
10353:                     if ($type eq 'Community') {
10354:                         next unless ($parent eq 'communities');
10355:                     } else {
10356:                         next if ($parent eq 'communities');
10357:                     }
10358:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10359:                     my $item = &escape($parent).'::0';
10360:                     my $checked = '';
10361:                     if (@currcategories > 0) {
10362:                         if (grep(/^\Q$item\E$/,@currcategories)) {
10363:                             $checked = ' checked="checked"';
10364:                         }
10365:                     }
10366:                     my $parent_title = $parent;
10367:                     if ($parent eq 'communities') {
10368:                         $parent_title = &mt('Communities');
10369:                     }
10370:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
10371:                               '<input type="checkbox" name="usecategory" value="'.
10372:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
10373:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
10374:                     my $depth = 1;
10375:                     push(@path,$parent);
10376:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
10377:                     pop(@path);
10378:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10379:                     $itemcount ++;
10380:                 }
10381:                 if ($itemcount) {
10382:                     $output = &Apache::loncommon::start_data_table().
10383:                               $table.
10384:                               &Apache::loncommon::end_data_table();
10385:                 }
10386:             }
10387:         }
10388:     }
10389:     return $output;
10390: }
10391: 
10392: =pod
10393: 
10394: =item *&assign_category_rows()
10395: 
10396: Create a datatable row for display of nested categories in a domain,
10397: with checkboxes to allow a course to be categorized,called recursively.
10398: 
10399: Inputs:
10400: 
10401: itemcount - track row number for alternating colors
10402: 
10403: cats - reference to array of arrays/hashes which encapsulates hierarchy of
10404:       categories and subcategories.
10405: 
10406: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
10407: 
10408: parent - parent of current category item
10409: 
10410: path - Array containing all categories back up through the hierarchy from the
10411:        current category to the top level.
10412: 
10413: currcategories - reference to array of current categories assigned to the course
10414: 
10415: Returns: $output (markup to be displayed).
10416: 
10417: =cut
10418: 
10419: sub assign_category_rows {
10420:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
10421:     my ($text,$name,$item,$chgstr);
10422:     if (ref($cats) eq 'ARRAY') {
10423:         my $maxdepth = scalar(@{$cats});
10424:         if (ref($cats->[$depth]) eq 'HASH') {
10425:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10426:                 my $numchildren = @{$cats->[$depth]{$parent}};
10427:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10428:                 $text .= '<td><table class="LC_datatable">';
10429:                 for (my $j=0; $j<$numchildren; $j++) {
10430:                     $name = $cats->[$depth]{$parent}[$j];
10431:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
10432:                     my $deeper = $depth+1;
10433:                     my $checked = '';
10434:                     if (ref($currcategories) eq 'ARRAY') {
10435:                         if (@{$currcategories} > 0) {
10436:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
10437:                                 $checked = ' checked="checked"';
10438:                             }
10439:                         }
10440:                     }
10441:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
10442:                              '<input type="checkbox" name="usecategory" value="'.
10443:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
10444:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
10445:                              '</td><td>';
10446:                     if (ref($path) eq 'ARRAY') {
10447:                         push(@{$path},$name);
10448:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10449:                         pop(@{$path});
10450:                     }
10451:                     $text .= '</td></tr>';
10452:                 }
10453:                 $text .= '</table></td>';
10454:             }
10455:         }
10456:     }
10457:     return $text;
10458: }
10459: 
10460: ############################################################
10461: ############################################################
10462: 
10463: 
10464: sub commit_customrole {
10465:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10466:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10467:                          ($start?', '.&mt('starting').' '.localtime($start):'').
10468:                          ($end?', ending '.localtime($end):'').': <b>'.
10469:               &Apache::lonnet::assigncustomrole(
10470:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10471:                  '</b><br />';
10472:     return $output;
10473: }
10474: 
10475: sub commit_standardrole {
10476:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10477:     my ($output,$logmsg,$linefeed);
10478:     if ($context eq 'auto') {
10479:         $linefeed = "\n";
10480:     } else {
10481:         $linefeed = "<br />\n";
10482:     }  
10483:     if ($three eq 'st') {
10484:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10485:                                          $one,$two,$sec,$context);
10486:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
10487:             ($result eq 'unknown_course') || ($result eq 'refused')) {
10488:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
10489:         } else {
10490:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10491:                ($start?', '.&mt('starting').' '.localtime($start):'').
10492:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10493:             if ($context eq 'auto') {
10494:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10495:             } else {
10496:                $output .= '<b>'.$result.'</b>'.$linefeed.
10497:                &mt('Add to classlist').': <b>ok</b>';
10498:             }
10499:             $output .= $linefeed;
10500:         }
10501:     } else {
10502:         $output = &mt('Assigning').' '.$three.' in '.$url.
10503:                ($start?', '.&mt('starting').' '.localtime($start):'').
10504:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10505:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10506:         if ($context eq 'auto') {
10507:             $output .= $result.$linefeed;
10508:         } else {
10509:             $output .= '<b>'.$result.'</b>'.$linefeed;
10510:         }
10511:     }
10512:     return $output;
10513: }
10514: 
10515: sub commit_studentrole {
10516:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10517:     my ($result,$linefeed,$oldsecurl,$newsecurl);
10518:     if ($context eq 'auto') {
10519:         $linefeed = "\n";
10520:     } else {
10521:         $linefeed = '<br />'."\n";
10522:     }
10523:     if (defined($one) && defined($two)) {
10524:         my $cid=$one.'_'.$two;
10525:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10526:         my $secchange = 0;
10527:         my $expire_role_result;
10528:         my $modify_section_result;
10529:         if ($oldsec ne '-1') { 
10530:             if ($oldsec ne $sec) {
10531:                 $secchange = 1;
10532:                 my $now = time;
10533:                 my $uurl='/'.$cid;
10534:                 $uurl=~s/\_/\//g;
10535:                 if ($oldsec) {
10536:                     $uurl.='/'.$oldsec;
10537:                 }
10538:                 $oldsecurl = $uurl;
10539:                 $expire_role_result = 
10540:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10541:                 if ($env{'request.course.sec'} ne '') { 
10542:                     if ($expire_role_result eq 'refused') {
10543:                         my @roles = ('st');
10544:                         my @statuses = ('previous');
10545:                         my @roledoms = ($one);
10546:                         my $withsec = 1;
10547:                         my %roleshash = 
10548:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10549:                                               \@statuses,\@roles,\@roledoms,$withsec);
10550:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10551:                             my ($oldstart,$oldend) = 
10552:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10553:                             if ($oldend > 0 && $oldend <= $now) {
10554:                                 $expire_role_result = 'ok';
10555:                             }
10556:                         }
10557:                     }
10558:                 }
10559:                 $result = $expire_role_result;
10560:             }
10561:         }
10562:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10563:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10564:             if ($modify_section_result =~ /^ok/) {
10565:                 if ($secchange == 1) {
10566:                     if ($sec eq '') {
10567:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10568:                     } else {
10569:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10570:                     }
10571:                 } elsif ($oldsec eq '-1') {
10572:                     if ($sec eq '') {
10573:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10574:                     } else {
10575:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10576:                     }
10577:                 } else {
10578:                     if ($sec eq '') {
10579:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10580:                     } else {
10581:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10582:                     }
10583:                 }
10584:             } else {
10585:                 if ($secchange) {       
10586:                     $$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;
10587:                 } else {
10588:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10589:                 }
10590:             }
10591:             $result = $modify_section_result;
10592:         } elsif ($secchange == 1) {
10593:             if ($oldsec eq '') {
10594:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10595:             } else {
10596:                 $$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;
10597:             }
10598:             if ($expire_role_result eq 'refused') {
10599:                 my $newsecurl = '/'.$cid;
10600:                 $newsecurl =~ s/\_/\//g;
10601:                 if ($sec ne '') {
10602:                     $newsecurl.='/'.$sec;
10603:                 }
10604:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10605:                     if ($sec eq '') {
10606:                         $$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;
10607:                     } else {
10608:                         $$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;
10609:                     }
10610:                 }
10611:             }
10612:         }
10613:     } else {
10614:         $$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;
10615:         $result = "error: incomplete course id\n";
10616:     }
10617:     return $result;
10618: }
10619: 
10620: ############################################################
10621: ############################################################
10622: 
10623: sub check_clone {
10624:     my ($args,$linefeed) = @_;
10625:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10626:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10627:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10628:     my $clonemsg;
10629:     my $can_clone = 0;
10630:     my $lctype = lc($args->{'crstype'});
10631:     if ($lctype ne 'community') {
10632:         $lctype = 'course';
10633:     }
10634:     if ($clonehome eq 'no_host') {
10635:         if ($args->{'crstype'} eq 'Community') {
10636:             $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'});
10637:         } else {
10638:             $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'});
10639:         }     
10640:     } else {
10641: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10642:         if ($args->{'crstype'} eq 'Community') {
10643:             if ($clonedesc{'type'} ne 'Community') {
10644:                  $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'});
10645:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10646:             }
10647:         }
10648: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10649:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10650: 	    $can_clone = 1;
10651: 	} else {
10652: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10653: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10654: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10655:             if (grep(/^\*$/,@cloners)) {
10656:                 $can_clone = 1;
10657:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10658:                 $can_clone = 1;
10659:             } else {
10660:                 my $ccrole = 'cc';
10661:                 if ($args->{'crstype'} eq 'Community') {
10662:                     $ccrole = 'co';
10663:                 }
10664: 	        my %roleshash =
10665: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10666: 					 $args->{'ccdomain'},
10667:                                          'userroles',['active'],[$ccrole],
10668: 					 [$args->{'clonedomain'}]);
10669: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10670:                     $can_clone = 1;
10671:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10672:                     $can_clone = 1;
10673:                 } else {
10674:                     if ($args->{'crstype'} eq 'Community') {
10675:                         $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'});
10676:                     } else {
10677:                         $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'});
10678:                     }
10679: 	        }
10680: 	    }
10681:         }
10682:     }
10683:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
10684: }
10685: 
10686: sub construct_course {
10687:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10688:     my $outcome;
10689:     my $linefeed =  '<br />'."\n";
10690:     if ($context eq 'auto') {
10691:         $linefeed = "\n";
10692:     }
10693: 
10694: #
10695: # Are we cloning?
10696: #
10697:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
10698:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10699: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10700: 	if ($context ne 'auto') {
10701:             if ($clonemsg ne '') {
10702: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10703:             }
10704: 	}
10705: 	$outcome .= $clonemsg.$linefeed;
10706: 
10707:         if (!$can_clone) {
10708: 	    return (0,$outcome);
10709: 	}
10710:     }
10711: 
10712: #
10713: # Open course
10714: #
10715:     my $crstype = lc($args->{'crstype'});
10716:     my %cenv=();
10717:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10718:                                              $args->{'cdescr'},
10719:                                              $args->{'curl'},
10720:                                              $args->{'course_home'},
10721:                                              $args->{'nonstandard'},
10722:                                              $args->{'crscode'},
10723:                                              $args->{'ccuname'}.':'.
10724:                                              $args->{'ccdomain'},
10725:                                              $args->{'crstype'},
10726:                                              $cnum,$context,$category);
10727: 
10728:     # Note: The testing routines depend on this being output; see 
10729:     # Utils::Course. This needs to at least be output as a comment
10730:     # if anyone ever decides to not show this, and Utils::Course::new
10731:     # will need to be suitably modified.
10732:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10733:     if ($$courseid =~ /^error:/) {
10734:         return (0,$outcome);
10735:     }
10736: 
10737: #
10738: # Check if created correctly
10739: #
10740:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10741:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10742:     if ($crsuhome eq 'no_host') {
10743:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10744:         return (0,$outcome);
10745:     }
10746:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10747: 
10748: #
10749: # Do the cloning
10750: #   
10751:     if ($can_clone && $cloneid) {
10752: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10753: 	if ($context ne 'auto') {
10754: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10755: 	}
10756: 	$outcome .= $clonemsg.$linefeed;
10757: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10758: # Copy all files
10759: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10760: # Restore URL
10761: 	$cenv{'url'}=$oldcenv{'url'};
10762: # Restore title
10763: 	$cenv{'description'}=$oldcenv{'description'};
10764: # Restore creation date, creator and creation context.
10765:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
10766:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
10767:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
10768: # Mark as cloned
10769: 	$cenv{'clonedfrom'}=$cloneid;
10770: # Need to clone grading mode
10771:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10772:         $cenv{'grading'}=$newenv{'grading'};
10773: # Do not clone these environment entries
10774:         &Apache::lonnet::del('environment',
10775:                   ['default_enrollment_start_date',
10776:                    'default_enrollment_end_date',
10777:                    'question.email',
10778:                    'policy.email',
10779:                    'comment.email',
10780:                    'pch.users.denied',
10781:                    'plc.users.denied',
10782:                    'hidefromcat',
10783:                    'categories'],
10784:                    $$crsudom,$$crsunum);
10785:     }
10786: 
10787: #
10788: # Set environment (will override cloned, if existing)
10789: #
10790:     my @sections = ();
10791:     my @xlists = ();
10792:     if ($args->{'crstype'}) {
10793:         $cenv{'type'}=$args->{'crstype'};
10794:     }
10795:     if ($args->{'crsid'}) {
10796:         $cenv{'courseid'}=$args->{'crsid'};
10797:     }
10798:     if ($args->{'crscode'}) {
10799:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10800:     }
10801:     if ($args->{'crsquota'} ne '') {
10802:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10803:     } else {
10804:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10805:     }
10806:     if ($args->{'ccuname'}) {
10807:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10808:                                         ':'.$args->{'ccdomain'};
10809:     } else {
10810:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10811:     }
10812:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10813:     if ($args->{'crssections'}) {
10814:         $cenv{'internal.sectionnums'} = '';
10815:         if ($args->{'crssections'} =~ m/,/) {
10816:             @sections = split/,/,$args->{'crssections'};
10817:         } else {
10818:             $sections[0] = $args->{'crssections'};
10819:         }
10820:         if (@sections > 0) {
10821:             foreach my $item (@sections) {
10822:                 my ($sec,$gp) = split/:/,$item;
10823:                 my $class = $args->{'crscode'}.$sec;
10824:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10825:                 $cenv{'internal.sectionnums'} .= $item.',';
10826:                 unless ($addcheck eq 'ok') {
10827:                     push @badclasses, $class;
10828:                 }
10829:             }
10830:             $cenv{'internal.sectionnums'} =~ s/,$//;
10831:         }
10832:     }
10833: # do not hide course coordinator from staff listing, 
10834: # even if privileged
10835:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10836: # add crosslistings
10837:     if ($args->{'crsxlist'}) {
10838:         $cenv{'internal.crosslistings'}='';
10839:         if ($args->{'crsxlist'} =~ m/,/) {
10840:             @xlists = split/,/,$args->{'crsxlist'};
10841:         } else {
10842:             $xlists[0] = $args->{'crsxlist'};
10843:         }
10844:         if (@xlists > 0) {
10845:             foreach my $item (@xlists) {
10846:                 my ($xl,$gp) = split/:/,$item;
10847:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10848:                 $cenv{'internal.crosslistings'} .= $item.',';
10849:                 unless ($addcheck eq 'ok') {
10850:                     push @badclasses, $xl;
10851:                 }
10852:             }
10853:             $cenv{'internal.crosslistings'} =~ s/,$//;
10854:         }
10855:     }
10856:     if ($args->{'autoadds'}) {
10857:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
10858:     }
10859:     if ($args->{'autodrops'}) {
10860:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
10861:     }
10862: # check for notification of enrollment changes
10863:     my @notified = ();
10864:     if ($args->{'notify_owner'}) {
10865:         if ($args->{'ccuname'} ne '') {
10866:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10867:         }
10868:     }
10869:     if ($args->{'notify_dc'}) {
10870:         if ($uname ne '') { 
10871:             push(@notified,$uname.':'.$udom);
10872:         }
10873:     }
10874:     if (@notified > 0) {
10875:         my $notifylist;
10876:         if (@notified > 1) {
10877:             $notifylist = join(',',@notified);
10878:         } else {
10879:             $notifylist = $notified[0];
10880:         }
10881:         $cenv{'internal.notifylist'} = $notifylist;
10882:     }
10883:     if (@badclasses > 0) {
10884:         my %lt=&Apache::lonlocal::texthash(
10885:                 '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',
10886:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10887:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10888:         );
10889:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10890:                            ' ('.$lt{'adby'}.')';
10891:         if ($context eq 'auto') {
10892:             $outcome .= $badclass_msg.$linefeed;
10893:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10894:             foreach my $item (@badclasses) {
10895:                 if ($context eq 'auto') {
10896:                     $outcome .= " - $item\n";
10897:                 } else {
10898:                     $outcome .= "<li>$item</li>\n";
10899:                 }
10900:             }
10901:             if ($context eq 'auto') {
10902:                 $outcome .= $linefeed;
10903:             } else {
10904:                 $outcome .= "</ul><br /><br /></div>\n";
10905:             }
10906:         } 
10907:     }
10908:     if ($args->{'no_end_date'}) {
10909:         $args->{'endaccess'} = 0;
10910:     }
10911:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10912:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10913:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10914:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10915:     if ($args->{'showphotos'}) {
10916:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10917:     }
10918:     $cenv{'internal.authtype'} = $args->{'authtype'};
10919:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10920:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10921:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10922:             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'); 
10923:             if ($context eq 'auto') {
10924:                 $outcome .= $krb_msg;
10925:             } else {
10926:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10927:             }
10928:             $outcome .= $linefeed;
10929:         }
10930:     }
10931:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10932:        if ($args->{'setpolicy'}) {
10933:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10934:        }
10935:        if ($args->{'setcontent'}) {
10936:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10937:        }
10938:     }
10939:     if ($args->{'reshome'}) {
10940: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10941: 	$cenv{'reshome'}=~s/\/+$/\//;
10942:     }
10943: #
10944: # course has keyed access
10945: #
10946:     if ($args->{'setkeys'}) {
10947:        $cenv{'keyaccess'}='yes';
10948:     }
10949: # if specified, key authority is not course, but user
10950: # only active if keyaccess is yes
10951:     if ($args->{'keyauth'}) {
10952: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10953: 	$user = &LONCAPA::clean_username($user);
10954: 	$domain = &LONCAPA::clean_username($domain);
10955: 	if ($user ne '' && $domain ne '') {
10956: 	    $cenv{'keyauth'}=$user.':'.$domain;
10957: 	}
10958:     }
10959: 
10960:     if ($args->{'disresdis'}) {
10961:         $cenv{'pch.roles.denied'}='st';
10962:     }
10963:     if ($args->{'disablechat'}) {
10964:         $cenv{'plc.roles.denied'}='st';
10965:     }
10966: 
10967:     # Record we've not yet viewed the Course Initialization Helper for this 
10968:     # course
10969:     $cenv{'course.helper.not.run'} = 1;
10970:     #
10971:     # Use new Randomseed
10972:     #
10973:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10974:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10975:     #
10976:     # The encryption code and receipt prefix for this course
10977:     #
10978:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10979:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10980:     #
10981:     # By default, use standard grading
10982:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10983: 
10984:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10985:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10986: #
10987: # Open all assignments
10988: #
10989:     if ($args->{'openall'}) {
10990:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10991:        my %storecontent = ($storeunder         => time,
10992:                            $storeunder.'.type' => 'date_start');
10993:        
10994:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10995:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10996:    }
10997: #
10998: # Set first page
10999: #
11000:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
11001: 	    || ($cloneid)) {
11002: 	use LONCAPA::map;
11003: 	$outcome .= &mt('Setting first resource').': ';
11004: 
11005: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
11006:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
11007: 
11008:         $outcome .= ($fatal?$errtext:'read ok').' - ';
11009:         my $title; my $url;
11010:         if ($args->{'firstres'} eq 'syl') {
11011: 	    $title=&mt('Syllabus');
11012:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
11013:         } else {
11014:             $title=&mt('Table of Contents');
11015:             $url='/adm/navmaps';
11016:         }
11017: 
11018:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
11019: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
11020: 
11021: 	if ($errtext) { $fatal=2; }
11022:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
11023:     }
11024: 
11025:     return (1,$outcome);
11026: }
11027: 
11028: ############################################################
11029: ############################################################
11030: 
11031: #SD
11032: # only Community and Course, or anything else?
11033: sub course_type {
11034:     my ($cid) = @_;
11035:     if (!defined($cid)) {
11036:         $cid = $env{'request.course.id'};
11037:     }
11038:     if (defined($env{'course.'.$cid.'.type'})) {
11039:         return $env{'course.'.$cid.'.type'};
11040:     } else {
11041:         return 'Course';
11042:     }
11043: }
11044: 
11045: sub group_term {
11046:     my $crstype = &course_type();
11047:     my %names = (
11048:                   'Course' => 'group',
11049:                   'Community' => 'group',
11050:                 );
11051:     return $names{$crstype};
11052: }
11053: 
11054: sub course_types {
11055:     my @types = ('official','unofficial','community');
11056:     my %typename = (
11057:                          official   => 'Official course',
11058:                          unofficial => 'Unofficial course',
11059:                          community  => 'Community',
11060:                    );
11061:     return (\@types,\%typename);
11062: }
11063: 
11064: sub icon {
11065:     my ($file)=@_;
11066:     my $curfext = lc((split(/\./,$file))[-1]);
11067:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
11068:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
11069:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
11070: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
11071: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11072: 	            $curfext.".gif") {
11073: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11074: 		$curfext.".gif";
11075: 	}
11076:     }
11077:     return &lonhttpdurl($iconname);
11078: } 
11079: 
11080: sub lonhttpdurl {
11081: #
11082: # Had been used for "small fry" static images on separate port 8080.
11083: # Modify here if lightweight http functionality desired again.
11084: # Currently eliminated due to increasing firewall issues.
11085: #
11086:     my ($url)=@_;
11087:     return $url;
11088: }
11089: 
11090: sub connection_aborted {
11091:     my ($r)=@_;
11092:     $r->print(" ");$r->rflush();
11093:     my $c = $r->connection;
11094:     return $c->aborted();
11095: }
11096: 
11097: #    Escapes strings that may have embedded 's that will be put into
11098: #    strings as 'strings'.
11099: sub escape_single {
11100:     my ($input) = @_;
11101:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
11102:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
11103:     return $input;
11104: }
11105: 
11106: #  Same as escape_single, but escape's "'s  This 
11107: #  can be used for  "strings"
11108: sub escape_double {
11109:     my ($input) = @_;
11110:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
11111:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
11112:     return $input;
11113: }
11114:  
11115: #   Escapes the last element of a full URL.
11116: sub escape_url {
11117:     my ($url)   = @_;
11118:     my @urlslices = split(/\//, $url,-1);
11119:     my $lastitem = &escape(pop(@urlslices));
11120:     return join('/',@urlslices).'/'.$lastitem;
11121: }
11122: 
11123: sub compare_arrays {
11124:     my ($arrayref1,$arrayref2) = @_;
11125:     my (@difference,%count);
11126:     @difference = ();
11127:     %count = ();
11128:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
11129:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
11130:         foreach my $element (keys(%count)) {
11131:             if ($count{$element} == 1) {
11132:                 push(@difference,$element);
11133:             }
11134:         }
11135:     }
11136:     return @difference;
11137: }
11138: 
11139: # -------------------------------------------------------- Initialize user login
11140: sub init_user_environment {
11141:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
11142:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
11143: 
11144:     my $public=($username eq 'public' && $domain eq 'public');
11145: 
11146: # See if old ID present, if so, remove
11147: 
11148:     my ($filename,$cookie,$userroles);
11149:     my $now=time;
11150: 
11151:     if ($public) {
11152: 	my $max_public=100;
11153: 	my $oldest;
11154: 	my $oldest_time=0;
11155: 	for(my $next=1;$next<=$max_public;$next++) {
11156: 	    if (-e $lonids."/publicuser_$next.id") {
11157: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
11158: 		if ($mtime<$oldest_time || !$oldest_time) {
11159: 		    $oldest_time=$mtime;
11160: 		    $oldest=$next;
11161: 		}
11162: 	    } else {
11163: 		$cookie="publicuser_$next";
11164: 		last;
11165: 	    }
11166: 	}
11167: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
11168:     } else {
11169: 	# if this isn't a robot, kill any existing non-robot sessions
11170: 	if (!$args->{'robot'}) {
11171: 	    opendir(DIR,$lonids);
11172: 	    while ($filename=readdir(DIR)) {
11173: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
11174: 		    unlink($lonids.'/'.$filename);
11175: 		}
11176: 	    }
11177: 	    closedir(DIR);
11178: 	}
11179: # Give them a new cookie
11180: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
11181: 		                   : $now.$$.int(rand(10000)));
11182: 	$cookie="$username\_$id\_$domain\_$authhost";
11183:     
11184: # Initialize roles
11185: 
11186: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
11187:     }
11188: # ------------------------------------ Check browser type and MathML capability
11189: 
11190:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
11191:         $clientunicode,$clientos) = &decode_user_agent($r);
11192: 
11193: # ------------------------------------------------------------- Get environment
11194: 
11195:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
11196:     my ($tmp) = keys(%userenv);
11197:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11198:     } else {
11199: 	undef(%userenv);
11200:     }
11201:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
11202: 	$form->{'interface'}=$userenv{'interface'};
11203:     }
11204:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
11205: 
11206: # --------------- Do not trust query string to be put directly into environment
11207:     foreach my $option ('interface','localpath','localres') {
11208:         $form->{$option}=~s/[\n\r\=]//gs;
11209:     }
11210: # --------------------------------------------------------- Write first profile
11211: 
11212:     {
11213: 	my %initial_env = 
11214: 	    ("user.name"          => $username,
11215: 	     "user.domain"        => $domain,
11216: 	     "user.home"          => $authhost,
11217: 	     "browser.type"       => $clientbrowser,
11218: 	     "browser.version"    => $clientversion,
11219: 	     "browser.mathml"     => $clientmathml,
11220: 	     "browser.unicode"    => $clientunicode,
11221: 	     "browser.os"         => $clientos,
11222: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
11223: 	     "request.course.fn"  => '',
11224: 	     "request.course.uri" => '',
11225: 	     "request.course.sec" => '',
11226: 	     "request.role"       => 'cm',
11227: 	     "request.role.adv"   => $env{'user.adv'},
11228: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
11229: 
11230:         if ($form->{'localpath'}) {
11231: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
11232: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
11233:         }
11234: 	
11235: 	if ($form->{'interface'}) {
11236: 	    $form->{'interface'}=~s/\W//gs;
11237: 	    $initial_env{"browser.interface"} = $form->{'interface'};
11238: 	    $env{'browser.interface'}=$form->{'interface'};
11239: 	}
11240: 
11241:         my %is_adv = ( is_adv => $env{'user.adv'} );
11242:         my %domdef = &Apache::lonnet::get_domain_defaults($domain);
11243: 
11244:         foreach my $tool ('aboutme','blog','portfolio') {
11245:             $userenv{'availabletools.'.$tool} = 
11246:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
11247:                                                   undef,\%userenv,\%domdef,\%is_adv);
11248:         }
11249: 
11250:         foreach my $crstype ('official','unofficial','community') {
11251:             $userenv{'canrequest.'.$crstype} =
11252:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
11253:                                                   'reload','requestcourses',
11254:                                                   \%userenv,\%domdef,\%is_adv);
11255:         }
11256: 
11257: 	$env{'user.environment'} = "$lonids/$cookie.id";
11258: 	
11259: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
11260: 		 &GDBM_WRCREAT(),0640)) {
11261: 	    &_add_to_env(\%disk_env,\%initial_env);
11262: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
11263: 	    &_add_to_env(\%disk_env,$userroles);
11264: 	    if (ref($args->{'extra_env'})) {
11265: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
11266: 	    }
11267: 	    untie(%disk_env);
11268: 	} else {
11269: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
11270: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
11271: 	    return 'error: '.$!;
11272: 	}
11273:     }
11274:     $env{'request.role'}='cm';
11275:     $env{'request.role.adv'}=$env{'user.adv'};
11276:     $env{'browser.type'}=$clientbrowser;
11277: 
11278:     return $cookie;
11279: 
11280: }
11281: 
11282: sub _add_to_env {
11283:     my ($idf,$env_data,$prefix) = @_;
11284:     if (ref($env_data) eq 'HASH') {
11285:         while (my ($key,$value) = each(%$env_data)) {
11286: 	    $idf->{$prefix.$key} = $value;
11287: 	    $env{$prefix.$key}   = $value;
11288:         }
11289:     }
11290: }
11291: 
11292: # --- Get the symbolic name of a problem and the url
11293: sub get_symb {
11294:     my ($request,$silent) = @_;
11295:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11296:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
11297:     if ($symb eq '') {
11298:         if (!$silent) {
11299:             $request->print("Unable to handle ambiguous references:$url:.");
11300:             return ();
11301:         }
11302:     }
11303:     &Apache::lonenc::check_decrypt(\$symb);
11304:     return ($symb);
11305: }
11306: 
11307: # --------------------------------------------------------------Get annotation
11308: 
11309: sub get_annotation {
11310:     my ($symb,$enc) = @_;
11311: 
11312:     my $key = $symb;
11313:     if (!$enc) {
11314:         $key =
11315:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
11316:     }
11317:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
11318:     return $annotation{$key};
11319: }
11320: 
11321: sub clean_symb {
11322:     my ($symb,$delete_enc) = @_;
11323: 
11324:     &Apache::lonenc::check_decrypt(\$symb);
11325:     my $enc = $env{'request.enc'};
11326:     if ($delete_enc) {
11327:         delete($env{'request.enc'});
11328:     }
11329: 
11330:     return ($symb,$enc);
11331: }
11332: 
11333: sub build_release_hashes {
11334:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
11335:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
11336:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
11337:                   (ref($randomizetry) eq 'HASH'));
11338:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
11339:         my ($item,$name,$value) = split(/:/,$key);
11340:         if ($item eq 'parameter') {
11341:             if (ref($checkparms->{$name}) eq 'ARRAY') {
11342:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
11343:                     push(@{$checkparms->{$name}},$value);
11344:                 }
11345:             } else {
11346:                 push(@{$checkparms->{$name}},$value);
11347:             }
11348:         } elsif ($item eq 'resourcetag') {
11349:             if ($name eq 'responsetype') {
11350:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
11351:             }
11352:         } elsif ($item eq 'course') {
11353:             if ($name eq 'crstype') {
11354:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
11355:             }
11356:         }
11357:     }
11358:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
11359:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
11360:     return;
11361: }
11362: 
11363: =pod
11364: 
11365: =back
11366: 
11367: =cut
11368: 
11369: 1;
11370: __END__;
11371: 

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